2017-01-20 45 views
1

我是全新使用sqlalchemypostgresql。我讀this教程構建下面的一段代碼:'模塊'對象無法用sqlalchemy調用

import sqlalchemy 
from sqlalchemy import create_engine 
from sqlalchemy import engine 


def connect(user, password, db, host='localhost', port=5432): 
    '''Returns a connection and a metadata object''' 
    # We connect with the help of the PostgreSQL URL 
    # postgresql://federer:[email protected]:5432/tennis 
    url = 'postgresql://{}:{}@{}:{}/{}' 
    url = url.format(user, password, host, port, db) 

    # The return value of create_engine() is our connection object 
    con = sqlalchemy.create_engine(url, client_encoding='utf8') 

    # We then bind the connection to MetaData() 
    meta = sqlalchemy.MetaData(bind=con, reflect=True) 

    return con, meta 

con, meta = connect('federer', 'grandestslam', 'tennis') 
con 
engine('postgresql://federer:***@localhost:5432/tennis') 
meta 
MetaData(bind=Engine('postgresql://federer:***@localhost:5432/tennis')) 

當運行它,我有這樣的錯誤:

File "test.py", line 22, in <module> 
    engine('postgresql://federer:***@localhost:5432/tennis') 
    TypeError: 'module' object is not callable 

我該怎麼辦?謝謝 !

+0

Did you import Engine?它來自哪裏? –

+0

@DanielRoseman對不起。我搞砸了,我發佈了一個已經解決的問題。我用真正的問題編輯了我的帖子。 –

+0

你是否也是Python的新手?你顯示的錯誤是不言自明的; 'engine'是一個模塊,你不能調用它。我不明白你在做什麼。 –

回答

2

所以,你的問題發生,因爲你做了這個調用:

from sqlalchemy import engine 

然後你用這個文件後面:

engine('postgresql://federer:***@localhost:5432/tennis') 

奇怪的是,在這一節中,你有一些陳述,只是conmeta沒有任何分配或通話或任何東西。我不確定你在那裏做什麼。我建議你檢查SQLalchemy的頁面engine and connection use,以幫助你排序。

這當然取決於你如何設置你的數據庫。我用declarative_base模塊在我的項目之一,所以我建立一個會話連接到我的數據庫的過程是這樣的:

from sqlalchemy import create_engine 
from sqlalchemy.orm import sessionmaker 

# Connect to Database and create database session 
engine = create_engine('postgresql://catalog:[email protected]/menus') 
Base.metadata.bind = engine 

DBSession = sessionmaker(bind=engine) 
session = DBSession() 

而且在我的數據庫安裝文件,我已經指派:

Base = declarative_base() 

但是你必須定製它到你的特定設置。我希望有所幫助。

編輯:我現在看到哪裏conmeta這些電話是從,以及你的其他混淆線來了,這是您鏈接到本教程的一部分。他在該教程中所做的是在命令行中使用Python解釋器。我會解釋他在那裏做的一些事情,希望能對你有所幫助。以>>>開頭的行是他作爲命令輸入的內容。其他行是他收到的輸出。

>>> con, meta = connect('federer', 'grandestslam', 'tennis') # he creates the connection and meta objects 
>>> con # now he calls the connection by itself to have it show that it's connected to his DB 
Engine(postgresql://federer:***@localhost:5432/tennis) 
>>> meta # here he calls his meta object to show how it, too, is connected 
MetaData(bind=Engine(postgresql://federer:***@localhost:5432/tennis)) 
+0

非常感謝這一切。我會盡力使你的建議與你的工作。也許還會找到另一個教程! –