Flask inherited classes of tables in multiple identical databases using __bind_key__

喜夏-厌秋 提交于 2019-12-02 03:03:34

The problem currently with SQLALCHEMY_BINDS is that it is only used for operations like create_all() or drop_all() - you need to change the session binding for that:

db.session.bind = db.get_engine(app, 'site2')

There's work ongoing to change that but it's not in the trunk yet.

Your code could be like:

db.session.bind = db.get_engine(app, orderObject.__bind_key__)
order = orderObject.query.get(orderid)

But remember that this changes the global session and does not reset it, you'd need to do that yourself or write a contextmanager so that you can use the with statement for that.

If your models are identical over all databases this could also be the way to only have one class for all databases, leave the bind_key and query them with a special bind session object.

Edit: with the Flask-SQLAlchemy 0.15 Release a simple MyModel.query.filter(...) is possible for different databases if you defined __bind_key__ properly.

db.Model.metadata.tables['your model name'].info['bind_key'] = 'your bind_name'

I found a way to make things easy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!