简体   繁体   English

flask-sqlalchemy交叉数据库,带有“动态”架构

[英]flask-sqlalchemy cross database with “dynamic” schema

I'm attempting to use the "application factory" pattern from flask, but I seem to have a chicken-and-egg problem with my models. 我正试图使用​​烧瓶中的“应用工厂”模式,但我的模型似乎有鸡与蛋的问题。 http://flask.pocoo.org/docs/patterns/appfactories/ http://flask.pocoo.org/docs/patterns/appfactories/

I am importing my views in the create_app function, which imports my models. 我在create_app函数中导入我的视图,该函数导入我的模型。 So, I don't have a config in the app when my models are being defined. 因此,在定义模型时,我在应用程序中没有配置。 This is usually fine, using the bind keys, I can set up models to connect to different dbs. 这通常很好,使用绑定键,我可以设置模型连接到不同的dbs。

However, in this case, I have two sets of models, one from the default database, and another set on another db connection - and I'd like to cross-db join. 但是,在这种情况下,我有两组模型,一组来自默认数据库,另一组是另一个数据库连接 - 我想交叉数据库连接。 I know that the usual method is to add 我知道通常的方法是添加

__table_args__ = { 'schema' : 'other_db_name' }

to my "other db" models. 到我的“其他数据库”模型。

But...depending on the config, the 'other_db_name' may be different. 但是......取决于配置,'other_db_name'可能不同。

So, now I have models being defined that require the schema name from the config, but with no schema from the config to put in the class definition. 所以,现在我定义的模型需要配置中的模式名称,但配置中没有模式放入类定义中。 I also may simply be missing something in flask I wasn't aware of. 我也可能只是遗漏了一些我不知道的烧瓶。

(Side note - an easy fix for this is to configure Sqlalchemy to always output the schema name in the query, no matter what - but I can't seem to find a setting for this.) (旁注 - 一个简单的解决方法是将Sqlalchemy配置为始终在查询中输出模式名称,无论如何 - 但我似乎无法找到此设置。)

If anyone has any input on this, I'd be very much obliged. 如果有人对此有任何意见,我将非常感激。 Thanks! 谢谢!

Never tried this myself, but you can probably force __table_args__ to have lazy evaluation by making it a declared_attr . 从未尝试过这个自己,但你也许可以强制__table_args__通过使其成为一个有懒惰的评估declared_attr

from sqlalchemy.ext.declarative import declared_attr

class MyModel(MySQLSettings, MyOtherMixin, Base):
    __tablename__='my_model'

    @declared_attr
    def __table_args__(cls):
        return { 'schema': current_app.config['OTHER_DB_NAME'] }

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

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