在 Pyramid 中使用 SQlAlchemy 声明性基础和 autoload=true
我对 Pyramid 还很陌生,我不知道如何在 Pyramid 中使用 autoload=true 选项。我使用 Pyramid_routesalchemy 来使用粘贴器创建我的项目。
问题是有一个 init.py 文件使用了initialize_sql(并且该函数定义了Base.metadata.bind = engine)。在我的模型类之一中,我想使用 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>
实际上 Base.metadata.bind = engine 是在initialize_sql函数中定义的,我并不真正知道知道文件加载的顺序,但我几乎确定 init.py 在模型之前加载,因此元数据已经绑定到引擎......
因此,我的问题:如何在我的类中使用自动加载不改变整体的情况下init 和模型结构?
如果有人有提示...提前致谢
I'm pretty new to Pyramid, and I can't figure out how to use the autoload=true option in Pyramid. I used the pyramid_routesalchemy to create my project using paster.
The problem is that there is an init.py file which uses the initialize_sql (and this function defines 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:
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...
Thus, my question: how can use autoload within my classes without changing the whole init and model structure ?
If anyone has a hint... Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这里的基本思想是,如果没有有效的引擎,则无法声明自动加载的表,因此您需要将初始化代码与模型代码分开,并确保在设置引擎并将其连接到之前不会导入模型元数据。
下面的链接描述得更好,但看起来您已经采取了正确的方法。
在 Pylons 中具有自动加载(反射)功能的 SQLAlchemy 声明性语法
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
从 SQLAlchemy 0.8 开始,您可以在创建声明性基础时使用 DeferredReflection 类来延迟自动加载,直到引擎附加到您的元数据:
请参见此处:http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#using-reflection-with-declarative
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:
See here: http://docs.sqlalchemy.org/en/rel_0_8/orm/extensions/declarative.html#using-reflection-with-declarative