Flask inherited classes of tables in multiple identical databases using __bind_key__

前端 未结 2 1114
别那么骄傲
别那么骄傲 2021-01-22 15:04

I\'m trying to build an admin control panel that brings together 4 different ecommerce sites. The sites all have identical database structures (all MySQL).

What\'s Goin

相关标签:
2条回答
  • 2021-01-22 15:41

    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.

    0 讨论(0)
  • 2021-01-22 15:43

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

    I found a way to make things easy

    0 讨论(0)
提交回复
热议问题