2010-02-28 26 views
1

我不斷收到錯誤,「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 

回答

0

鑑於你給的代碼不完整片段,唯一相關的信息是:

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

的錯誤指示是基本的Python類型錯誤,標量(或無)需要在SQLAlchemy中下標。這幾乎可以肯定是在你沒有顯示的部分代碼中完成或錯誤構建的會話的結果。

0

我的猜測是錯誤的是在這一行:

 
    shard.engine = shard_info['sqlite'] 

因爲shard_info是碎片類的唯一對象,我可以看到,這是在粘貼代碼的唯一訂閱操作。回溯顯示了不同的線條,因此您可能在導入後編輯了源代碼?

回到錯誤:SQLAlchemy的對象不是字典,那麼你想要的是

 
    shard.engine = shard_info.sqlite 

但會分配一個字符串(文件名SQLAlchemy的網址?)發動機,這是不是你應該被傳遞到Session.configure()。我猜你想要類似

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