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().

点赞