SQLAlchemy如何从Session查询对象获取响应?

时间:2017-04-20 05:30:10

标签: python postgresql session orm sqlalchemy

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

代码

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

1 个答案:

答案 0 :(得分:0)

我确实让代码正常工作。我没有在会话上正确格式化查询对象。

<强> CODE

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)

<强> TRACEBACK

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