在SQLAlchemy中使用declarative_base时,如何在需要时绑定引擎?

时间:2010-11-18 14:38:31

标签: python database orm sqlalchemy

这是我的代码:

from sqlalchemy import create_engine, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

database_url = 'mysql://some_path'
engine = create_engine(database_url)
Base = declarative_base(engine)

class Users(Base):
    __tablename__ = 'Users'
    __table_args__ = {'autoload':True}

metadata = Base.metadata
Session = sessionmaker(bind=engine)
session = Session()

它有效,但是......
是否有可能在我需要时绑定引擎,而不仅仅是在导入时?所以我可以将此实现包装到类中。

现在,我得到

    class Users(Base):
  File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/ext/declarative.py", line 1231, in __init__
    _as_declarative(cls, classname, cls.__dict__)
  File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/ext/declarative.py", line 1122, in _as_declarative
    **table_kw)
  File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/schema.py", line 209, in __new__
    table._init(name, metadata, *args, **kw)
  File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/schema.py", line 260, in _init
    msg="No engine is bound to this Table's MetaData. "
  File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.6.5-py2.5.egg/sqlalchemy/schema.py", line 2598, in _bind_or_error
    raise exc.UnboundExecutionError(msg)
sqlalchemy.exc.UnboundExecutionError: No engine is bound to this Table's MetaData. Pass an engine to the Table via autoload_with=<someengine>, or associate the MetaData with an engine via metadata.bind=<someengine>

未指定引擎时:Base = declarative_base()

2 个答案:

答案 0 :(得分:8)

至少使用SQLAlchemy 0.9,您可以使用DeferredReflection推迟绑定。请参阅Using Reflection with Declarative section of the manual中的示例。

在那里,您可以找到以下示例(简化):

from sqlalchemy.ext.declarative import declarative_base, DeferredReflection

Base = declarative_base(cls=DeferredReflection)

class Foo(Base):
    __tablename__ = 'foo'
    bars = relationship("Bar")

class Bar(Base):
    __tablename__ = 'bar'

Base.prepare(e)

是引擎。

答案 1 :(得分:0)

不,您不能使用设置为autoload的{​​{1}}选项的后期绑定,因为SQLAlchemy无法在不了解数据库架构的情况下编译映射器。