Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

I am importing my views in the create_app function, which imports my models. 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.

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.

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.)

If anyone has any input on this, I'd be very much obliged. Thanks!

like image 522
Hoopes Avatar asked Oct 03 '22 03:10

Hoopes


1 Answers

Never tried this myself, but you can probably force __table_args__ to have lazy evaluation by making it a 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'] }
like image 159
Miguel Avatar answered Oct 05 '22 16:10

Miguel