繁体   English   中英

无法从方法内部访问数据库

[英]Unable to access database from within a method

我不断收到错误消息,“ TypeError:'Shard'对象无法下标 。”

#Establish an on-demand connection to the central database
def connectCentral():
    engine = engine_from_config(config, 'sqlalchemy.central.')
    central.engine = engine
    central.Session.configure(bind=engine)

#Establish an on-demand connection to a shard that contains
#data for the supplied id
def connectShard(id):

    #If no connection has been made to the central database
    #make one to determine the shard info
    if central.engine == None:
        print 'Connecting to central database'
        connectCentral()

    shard_info = central.Session.query(Shard).filter_by(id=id).first()

    #If no shard exists for the given id, return false
    if shard_info == None:
        return 'None'

    shard.engine = shard_info['sqlite']
    shard.Session.configure(bind=shard.engine)

c_shard = sa.Table("Shard", central.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("ip",sa.types.String(100), nullable=False),
sa.Column("username",sa.types.String(100), nullable=False),
sa.Column("password",sa.types.String(100), nullable=False),
sa.Column("port",sa.types.String(100), nullable=False),
sa.Column("active",sa.types.String(100), nullable=False),
sa.Column("sqlite",sa.types.String(100), nullable=True)
)

错误输出为:

connectShard(232)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/project/project/model/__init__.py", line 39, in connectShard
    shard.Session.configure(bind=shard.engine)
TypeError: 'Shard' object is unsubscriptable

鉴于您提供的代码段不完整,唯一相关的行是:

shard.Session.configure(bind=shard.engine)

错误指示是基本的Python类型错误,需要在SQLAlchemy中添加标量(或“无”)。 这几乎可以肯定是由于未显示的部分代码中的会话不完整或错误构造造成的。

我的猜测是错误在这一行:

shard.engine = shard_info['sqlite']

因为shard_info是我可以看到的Shard类的唯一对象,并且是粘贴的代码中唯一的订阅操作。 追溯显示不同的行,所以也许您在导入源之后编辑了源?

回到错误:SQLAlchemy对象不是字典,所以您想要的是

shard.engine = shard_info.sqlite

但这会为引擎分配一个字符串(文件名?sqlalchemy url?),而不是您应该传递给Session.configure()的字符串。 我猜你想要类似的东西

dbname = shard_info.sqlite
    shard.engine = create_engine('sqlite:///' + dbname)
    shard.Session.configure(bind=shard.engine)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM