python - 在 SQLAlchemy 中使用 declarative_base 时,如何在需要时绑定(bind)引擎?

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

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

现在,我明白了

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

最佳答案

至少在 SQLAlchemy 0.9 中,您可以使用 DeferredReflection 延迟绑定(bind)。请参阅 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 是引擎。

关于python - 在 SQLAlchemy 中使用 declarative_base 时,如何在需要时绑定(bind)引擎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4215920/

相关文章:

python - 在pyspark中处理.txt文件数据并更改数据类型

python - DJANGO 将字段中的模型类型保存为通用外键

database - Sitecore 外部数据库集成

orm - 如何使用 ClojureQL 向表添加索引?

java - 关于 mongodb for Java 的 ORM 工具/框架

python - 可汗学院的语言本地化

python - Enthought python包导入优先级

mysql - 这两个简单的 SQL 查询有什么区别?

asp.net-mvc - 如何从数据库加载一次,然后使用静态方法检索数据?

java - 在同一 session 中将多个具有相同标识符的对象保存到数据库中?