【问题标题】:SQLAlchemy How to obtain a response from Session query object?SQLAlchemy 如何从 Session 查询对象获取响应?
【发布时间】:2017-09-16 13:56:27
【问题描述】:

我已经完成了SQLAlchemy ORM tutorial 的工作,现在正在将其调整到我自己的数据库中。我在尝试查询 Session 对象时遇到了 Postgres 方言的问题,但是我没有收到结果。我确信我错过了一些东西,并且可以使用一些方向来让它发挥作用,或者至少我应该研究什么。感谢您的帮助。

代码

import sqlalchemy
from sqlalchemy import create_engine, ForeignKey, Column, INTEGER
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import TEXT, NUMERIC, TIMESTAMP
from sqlalchemy.orm import sessionmaker

# CONNECTING
# create an instance of Engine, represents core interface to the db
engine = create_engine('postgresql://user:pass@ip:port/db', echo=True)

# DECLARE A MAPPING
# instantiate the Declarative base class for a catalog of classes & tables
# relative to the base class.
Base = declarative_base()

# map a table to a class by inheriting base class via declarative_base
class History_1m(Base):
    __tablename__ = 'history_1m'

    id = Column(INTEGER, primary_key=True, autoincrement=True)
    name = Column(TEXT)
    symbol = Column(TEXT)
    ask = Column(NUMERIC)
    bid = Column(NUMERIC)

# CREATE A SCHEMA
# using the engine, create our table via a method of the MetaData registry
Base.metadata.create_all(engine)

# CREATE AN INSTANCE OF MAPPED CLASS
# instantiate an instance of the User class and generate attribute values
symbol_data = History_1m()

# CREATING A SESSION
# define a Session class to talk with our db
Session = sessionmaker(bind=engine)
session = Session()
# in case of no engine yet, Session = sessionmaker() is acceptable
# to talk to the db you should use session = Session each time

# query the Session to verify the instance is pending
symbol = 'AAPL'
recent_symbol = session.query(History_1m).filter_by(symbol=symbol).first()

# print the contents of our_user, ed_user is our_user via identity map
print('\n> Do we have a symbol entry?\n', recent_symbol)
for row in session.query(History_1m).order_by(History_1m.id):
    print(row.name, row.symbol, row.ask, row.bid)

追溯

Microsoft Corporation MSFT 65.52 65.51
Adobe Systems Incorporated ADBE 131.85 131.83
Cytori Therapeutics Inc CYTX 1.04 1.03
Whole Foods Market, Inc. WFM 35.58 35.57
None None None None

进程以退出代码 0 结束

【问题讨论】:

  • 目前尚不清楚您从哪里获得NameError。你的例子不应该产生它。请同时包含verifiable example 和您获得的回溯。或者重写你的标题和问题。至于获取None,您确定您的数据库包含name = 'AAPL' 的行,还是您的意思是filter_by(symbol=symbol)?您是否连接到正确的数据库?
  • 您好 Ilja,我已将问题重新命名,并将输出部分更改为 Traceback。我知道我正在连接到正确的数据库。我相信您在我寻找符号而不是名称字段的地方是正确的。
  • 不完全确定您所说的“在将 symbol_data 添加到会话并对其进行查询之前,我必须为其创建映射类的实例吗?”,symbol_data = History_1m() 是多余的,因为您不会将其添加到会话中。它只是绑定到名称 symbol_dataHistory_1m 类的一个新的未使用实例,没什么特别的。回溯是您与异常一起获得的输出,并包含堆栈跟踪等。我要求它,因为您的原始标题暗示了异常。显然,您的原始查询的问题只是列错误(名称与符号)。
  • 总而言之,我认为您应该仔细阅读本教程,因为您似乎对术语和什么是什么感到有些困惑。
  • 谢谢,我明白你所说的 symbol_data 是多余的。我正在继续审查文档并取得良好进展。

标签: python postgresql session orm sqlalchemy


【解决方案1】:

我确实让代码工作了。我没有正确格式化会话中的查询对象。

代码

import sqlalchemy
from sqlalchemy import create_engine, ForeignKey, Column, INTEGER
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.postgresql import TEXT, NUMERIC, TIMESTAMP
from sqlalchemy.orm import sessionmaker

# CONNECTING
# create an instance of Engine, represents core interface to the db
engine = create_engine('postgresql://user:password@ip:pport/database', echo=True)

# DECLARE A MAPPING
# instantiate the Declarative base class for a catalog of classes & tables
# relative to the base class.
Base = declarative_base()

# map a table to a class by inheriting base class via declarative_base
class History_1m(Base):
    __tablename__ = 'history_1m'

    id = Column(INTEGER, primary_key=True, autoincrement=True)
    name = Column(TEXT)
    symbol = Column(TEXT)
    ask = Column(NUMERIC)
    bid = Column(NUMERIC)

# CREATE A SCHEMA
# using the engine, create our table via a method of the MetaData registry
Base.metadata.create_all(engine)

# CREATING A SESSION
# define a Session class to talk with our db
Session = sessionmaker(bind=engine)
# in case of no engine yet, Session = sessionmaker() is acceptable
# to talk to the db you should use session = Session each time

# query the Session for the first symbol entry
session = Session()
symbol = 'AAPL'
recent_symbol = session.query(History_1m).filter_by(symbol=symbol).first()

# print the contents of the response via identity map
print('\n> Do we have a symbol entry?\n', recent_symbol.name, recent_symbol.symbol,
      recent_symbol.ask, recent_symbol.bid)

追溯

C:\Users\User\Anaconda2\envs\python36_learning\python.exe D:/tech_indicators/sqla_orm_adapt.py
2017-04-20 12:45:33,470 INFO sqlalchemy.engine.base.Engine select version()
2017-04-20 12:45:33,470 INFO sqlalchemy.engine.base.Engine {}
2017-04-20 12:45:33,471 INFO sqlalchemy.engine.base.Engine select current_schema()
2017-04-20 12:45:33,471 INFO sqlalchemy.engine.base.Engine {}
2017-04-20 12:45:33,472 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1
2017-04-20 12:45:33,472 INFO sqlalchemy.engine.base.Engine {}
2017-04-20 12:45:33,473 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1
2017-04-20 12:45:33,473 INFO sqlalchemy.engine.base.Engine {}
2017-04-20 12:45:33,473 INFO sqlalchemy.engine.base.Engine show standard_conforming_strings
2017-04-20 12:45:33,473 INFO sqlalchemy.engine.base.Engine {}
2017-04-20 12:45:33,474 INFO sqlalchemy.engine.base.Engine select relname from pg_class c join pg_namespace n on n.oid=c.relnamespace where pg_catalog.pg_table_is_visible(c.oid) and relname=%(name)s
2017-04-20 12:45:33,474 INFO sqlalchemy.engine.base.Engine {'name': 'history_1m'}
2017-04-20 12:45:33,476 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2017-04-20 12:45:33,476 INFO sqlalchemy.engine.base.Engine SELECT history_1m.id AS history_1m_id, history_1m.name AS history_1m_name, history_1m.symbol AS history_1m_symbol, history_1m.ask AS history_1m_ask, history_1m.bid AS history_1m_bid 
FROM history_1m 
WHERE history_1m.symbol = %(symbol_1)s 
 LIMIT %(param_1)s
2017-04-20 12:45:33,477 INFO sqlalchemy.engine.base.Engine {'symbol_1': 'AAPL', 'param_1': 1}

> Do we have a symbol entry?
 Apple Inc. AAPL 141.08 141.07

Process finished with exit code 0

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 2013-05-03
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2022-01-25
    • 2014-08-21
    相关资源
    最近更新 更多