无法在Pyramid应用程序中将元数据绑定到SQLAlchemy的引擎

时间:2014-08-05 20:54:54

标签: python sqlalchemy pyramid

有人可以向我解释为什么这不起作用:

我的 init .py文件:

from pyramid.config import Configurator
from pyramid_jinja2 import renderer_factory
from sqlalchemy import engine_from_config

from .models import (DBSession, 
                Base,
                )

def main(global_config, **settings):
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind = engine)
    Base.metadata.bind = engine

    config = Configurator(settings = settings)
    config.include('pyramid_jinja2')

    #The views/routes are added here
    config.add_static_view('static', 'static')
    config.add_static_view('scripts', 'scripts')

    config.add_route("my_route", '/')
    config.add_route("sign_in", "/sign_in")
    config.add_route("sign_up", "/sign_up")
    config.add_route("main_page", "/{username}")
    config.scan()

    return config.make_wsgi_app()

我的models.py文件:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.schema import Table
from sqlalchemy import create_engine
from sqlalchemy.orm import (scoped_session, sessionmaker, synonym, relation, backref)
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
from zope.sqlalchemy import ZopeTransactionExtension


DBSession = scoped_session(sessionmaker(extension = ZopeTransactionExtension()))
Base = declarative_base(cls=DeferredReflection)


#Define your models here
class User(Base):
    __table__ = Table('users', Base.metadata, autoload = True)

我完全按照Pyramid教程(在 init .py中使用Base.metadata.bind = engine)的规定完成,但仍然出现错误:

“sqlalchemy.exc.UnboundExecutionError:没有引擎绑定到此Table的MetaData。通过autoload_with ='someengine'将引擎传递给表,或通过metadata.bind ='someengine'将MetaData与引擎关联”

2 个答案:

答案 0 :(得分:0)

在引擎绑定之前,您无法使用autoload。 SQLA尝试在模块初始化时反映users表,即使元数据尚未关联任何引擎。

我对此的“修复”是双重的 - 自定义表工厂:

def AutoloadedTable(*args, **kwargs):
    rv = Table(*args, **kwargs)
    rv.deferred_autoloading = True
    return rv

只会填充deferred_autoloading属性,以及>创建引擎后的以下代码段

from sqlalchemy.engine import reflection

inspector = reflection.Inspector.from_engine(engine)
for i in list(metadata.tables.values()):
    if getattr(i, 'deferred_autoloading', False):
        inspector.reflecttable(i, None)

答案 1 :(得分:0)

我已设法使用以下说明修复此问题:

http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative.html#using-reflection-with-declarative

并添加

Base.prepare(引擎)到 init .py文件中的主要功能