2010-11-18 23 views
5

Aquí está mi código:¿Cómo enlazar motor cuando quiero, cuando uso declarative_base en 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() 

Funciona, pero ...
¿Es posible unir el motor cuando quiero, no sólo en el momento de la importación? Entonces puedo envolver esta implementación en clase.

Por ahora, me sale

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> 

cuando el motor no se especifica: Base = declarative_base()

Respuesta

0

No, no se puede utilizar el enlace con autoload opción se ajusta a True, ya que no puede compilar SQLAlchemy mapeadores sin conocimiento del esquema de la base de datos.

8

Al menos con SQLAlchemy 0.9 puede aplazar el enlace utilizando DeferredReflection. Vea el ejemplo en el Using Reflection with Declarative section of the manual.

Allí, se puede encontrar el siguiente ejemplo (simplificado):

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 es el motor.

Cuestiones relacionadas