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

Posted

技术标签:

【中文标题】在 SQLAlchemy 中使用 declarative_base 时如何绑定引擎?【英文标题】:How to bind engine when I want, when using declarative_base in SQLAlchemy? 【发布时间】:2010-11-18 14:38:30 【问题描述】:

这是我的代码:

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

【问题讨论】:

【参考方案1】:

至少在 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)

e 是引擎。

【讨论】:

链接失效【参考方案2】:

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

【讨论】:

以上是关于在 SQLAlchemy 中使用 declarative_base 时如何绑定引擎?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 SQLAlchemy 模型中使用 SQLAlchemy Utils

如何在 SQLAlchemy 中使用 UUID?

SQLAlchemy模型中的进程字段(使用flask_sqlalchemy)

在 SQLAlchemy 中使用 OR

在 sqlalchemy 中使用 DATEADD

在烧瓶中使用 SqlAlchemy 模型