简体   繁体   English

在Pyramid中使用SQlAlchemy声明性base和autoload = true

[英]Using SQlAlchemy declarative base and autoload=true in Pyramid

I'm pretty new to Pyramid, and I can't figure out how to use the autoload=true option in Pyramid. 我对Pyramid很新,我无法弄清楚如何在Pyramid中使用autoload = true选项。 I used the pyramid_routesalchemy to create my project using paster. 我使用pyramid_routesalchemy使用贴纸创建我的项目。

The problem is that there is an init.py file which uses the initialize_sql (and this function defines Base.metadata.bind = engine). 问题是有一个init.py文件使用了initialize_sql(这个函数定义了Base.metadata.bind = engine)。 In one of my model classes I would like to use the autoload=true option (using the declarative base), but I always get the following error: 在我的一个模型类中,我想使用autoload = true选项(使用声明性基础),但我总是得到以下错误:

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>

Actually Base.metadata.bind = engine is defined inside the initialize_sql function and I do not realy know in which order the file are loaded, but I'm almost sure that that init.py is loaded before the model, and thus metadata was already binded to the engine... 实际上Base.metadata.bind = engine是在initialize_sql函数中定义的,我不知道文件加载的顺序,但我几乎可以肯定在模型之前加载了init.py,因此元数据已经是绑定到引擎......

Thus, my question: how can use autoload within my classes without changing the whole init and model structure ? 因此,我的问题是:如何在我的类中使用自动加载而不改变整个init和模型结构?

If anyone has a hint... Thanks in advance 如果有人有提示......提前谢谢

From SQLAlchemy 0.8 you can use the DeferredReflection class when creating your declarative base to delay the autoload until an engine is attached to your metadata: 从SQLAlchemy 0.8开始,您可以在创建声明性基础时使用DeferredReflection类来延迟自动加载,直到引擎连接到元数据:

from sqlalchemy.ext.declarative import declarative_base, DeferredReflection

Base = declarative_base(cls=DeferredReflection)

See here: http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#using-reflection-with-declarative 见这里: http//docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#using-reflection-with-declarative

Yeah, the basic idea here is that the autoloaded tables cannot be declared without a valid engine, so you need to separate your initialization code from your model code and ensure that the models aren't imported until you have setup the engine and connected it to the metadata. 是的,这里的基本思想是在没有有效引擎的情况下无法声明自动加载的表,因此您需要将初始化代码与模型代码分开,并确保在设置引擎并将其连接到模型之前不会导入模型元数据。

The link below describes it better, but it looks like you've already taken the correct approach. 下面的链接更好地描述了它,但看起来你已经采取了正确的方法。

SQLAlchemy declarative syntax with autoload (reflection) in Pylons 在Pylons中使用自动加载(反射)的SQLAlchemy声明性语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM