python - 具有多个数据库分片的 SQLAlchemy 声明模型

标签 python sqlalchemy

我试图将我的数据库分成两部分:一个用于我的主要对象,另一个用于日志。现在,我的代码看起来像这样:

engine = create_engine('postgresql+psycopg2://postgres:password@localhost:5432/logs')
engine2 = create_engine('postgresql+psycopg2://postgres:password@localhost:5432/logs')
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
binds = {'thing': engine,
    'log': engine_a}
DBSession.configure(binds=binds)
Base = declarative_base(bind=engine)
Base2 = declarative_base(bind=engine2)

class Thing(Base):
    ...

class Log(Base2):
    ...

我有更多的表同时使用 Base 和 Base2 以及继承的对象。我也尝试过执行以下操作:

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension(), bind=engine))
DBSession2 = scoped_session(sessionmaker(extension=ZopeTransactionExtension(), bind=engine2))

但是,无论使用哪种方式,并且只使用 Base 中的对象,而不是 Base2,我在查询时都会收到以下错误:

return DBSession.query(cls).filter(func.lower(cls.name) == name.lower()).first()
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/scoping.py", line 113, in do
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/session.py", line 969, in query
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/query.py", line 107, in __init__
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/query.py", line 116, in _set_entities
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/query.py", line 131, in _setup_aliasizers
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/util.py", line 550, in _entity_info
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/mapper.py", line 2861, in configure_mappers
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/mapper.py", line 1166, in _post_configure_properties
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/interfaces.py", line 128, in init
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/properties.py", line 913, in do_init
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/orm/properties.py", line 969, in _process_dependent_arguments
  File "build/bdist.macosx-10.7-intel/egg/sqlalchemy/ext/declarative.py", line 1346, in return_cls
  File "<string>", line 1, in <module>
AttributeError: 'Table' object has no attribute 'id'

当然,我的表有一个属性“id”,只要我只有一个 DBSession 和一个 Base,所有相同的代码都可以工作。我做错了什么?

最佳答案

我发现了问题。我只需启动 DBSession()

关于python - 具有多个数据库分片的 SQLAlchemy 声明模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8831568/

相关文章:

python - 在数据框上标记索引

python - 如何使用加载的数据在 ItemLoader 中添加新值?

python - SQLAlchemy mixin,如何从它们继承和变量关系

python - SQLAlchemy 将 bool 列转换为 int

python - SQLAlchemy 多对多连接

python - 在 model.fit() 期间记录 Keras 中每个时期的计算时间

python - 如何有效地从python中的列表中删除相同长度的元素

Python 的 asyncore 使用可变超时定期发送数据。有没有更好的办法?

python - 嵌套棉花糖和 Sqlalchemy 包括子项

python - 已为此 MetaData 实例定义表 'roles_users'