Как привязать движок, когда я хочу, при использовании declarative_base в 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 ()

5
задан kolobos 19 November 2010 в 00:03
поделиться