无法从方法中访问数据库

时间:2010-02-28 00:55:24

标签: python sqlalchemy pylons

我一直收到错误,“ 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

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

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

    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)