在SQLAlchemy中使用declarative_base时,如何在需要时绑定引擎? [英] How to bind engine when I want, when using declarative_base in SQLAlchemy?

查看:699
本文介绍了在SQLAlchemy中使用declarative_base时,如何在需要时绑定引擎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

它有效,但是...
是否可以在我想要的时候不仅在导入时绑定引擎?因此我可以将此实现包装到类中.

It works, but...
Is it possible to bind engine when I want, not only at import time? So I can wrap this implementation into class.

现在,我明白了

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

推荐答案

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

No, you can't use late binding with autoload option set to True, since SQLAlchemy can't compile mappers without knowledge of database schema.

这篇关于在SQLAlchemy中使用declarative_base时,如何在需要时绑定引擎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆