2017-04-20 117 views
-1

我已經通過了SQLAlchemy ORM tutorial,現在正在將它調整到我自己的數據庫。我遇到了Postgres方言的問題,我試圖查詢Session對象,但是我沒有收到結果。我相信我錯過了一些東西,並且可以利用一些方向來實現這個目標,或者至少我應該研究什麼。感謝您的幫助。SQLAlchemy如何從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:[email protected]: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

+4

你在哪裏讓你'NameError'目前還不清楚。你的例子不應該產生它。請同時包含一個[可驗證的示例](http://stackoverflow.com/help/mcve)以及您獲得的回溯。或者重寫你的標題和問題。至於獲得'None',你確定你的數據庫包含一個'name ='AAPL'的行,或者你的意思是'filter_by(symbol = symbol)'?你是否連接到正確的數據庫? –

+0

嗨Ilja,我重新命名了這個問題,並將輸出部分改爲Traceback。我知道我正在連接到正確的數據庫。我相信你是正確的,我正在尋找一個符號而不是名稱字段。 – Liquidgenius

+0

在將symbol_data添加到會話並查詢它之前,是否必須爲symbol_data創建映射類的實例?如果是這樣,有沒有一種簡單的方法可以將它映射到表中的所有列,而不是在symbol_data對象中隱式定義它們? (如果這甚至是問題。) – Liquidgenius

回答

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:[email protected]: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