我正在尝试使用dict构造一个sqlalchemy引擎,该dict具有从tkinter解析的变量

时间:2015-08-06 09:54:32

标签: python dictionary sqlalchemy

任何帮助都将非常感激。我有一个使用sqlalchemy的连接引擎,它完美连接。我想把它变成动态的,用户在tkinter Entry框中提供信息,然后将信息解析成一个dict,然后由一个函数调用,然后从那里创建引擎。

我的工作引擎是:

engine =    sqlalchemy.create_engine('postgresql+pg8000://myuser:mypass@localhost/mydb')

我想要这样的东西

sqlalchemy.create_engine('postgresql+pg8000://DBUSER:DBPASS@DBHOST/DBNAME')

其中变量首先由tkinter Entry提供并放入dict中,然后由连接函数读取。

我有以下

from sqlalchemy import create_engine
from sqlalchemy.engine import url

"""
These vars below are for testing. Ultimately they will be resolved
by a get() from tkinter which will take the values entered by a 
user into an Entry widget and place them into the dict below. 
The db_connect() func should build the url from the dict.
"""

DBNAME = 'mydb'
DBUSER = 'myuser'
DBPASS = 'password'
DBHOST ='localhost'
PNUM = '5432'
import json
import urllib.request as myurl

DATABASE = {
    'drivername': 'postgres+pg8000',
    'host': DBHOST,
    'port': PNUM,
    'username': DBUSER,
    'password': DBPASS,
    'database': DBNAME
}

def db_connect():
    create_engine(url(DATABASE))
"""This func should create the db engine connect


connect = sqlalchemy.create_engine(db_connect())

df = pd.read_sql("SELECT * FROM nc_data",con=connect)

我收到错误

db_connect         return create_engine(url(DATABASE))     TypeError:'module'对象不可调用

1 个答案:

答案 0 :(得分:5)

使用关键字参数

将其输入sqlalchemy的url.URL()函数
create_engine(url.URL(**DATABASE))

请注意**,正确的方法是url.URL(),而不仅仅是url http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#sqlalchemy.engine.url.URL

参考**做什么:https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists