Using different binds in the same class in Flask-S

2020-07-16 08:44发布

问题:

I currently have multiple databases with identical Tables and Columns (but different data inside). So clearly I need to use binds to access all of them, but it's apparently not as simple as doing this:

class WhateverTable(db.Model):
    __tablename__ = 'whatevertable'
    whatever = db.Column(db.String(255))

    def __init__(self, bind=None):
        self.__bind_key__ = bind

and then later calling:

WhateverTable(bind='bind_key_here').query.filter_by(whatever='whatever').first()

Is there a way I can do this easily? I've tried inheriting from a table class and then defining the bind there, and while that works, it really isn't scalable.

EDIT: This :Flask inherited classes of tables in multiple identical databases using __bind_key__ does sort of what I want, but I don't want to have different classes because if I ever add a new database, I'm going to have to create a new set of classes and relationships.

回答1:

Flask-SQLAlchemy 2.1 added support for a binds parameter on the session which should do what you want.