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.
Use a bind To use a binded database, you need to specify it with the bind_key attribute. Declare a model using database2 – which is binded to “db2”. Simply, using bind_key you've told Flask-SQLAlchemy to use the db2 (aka database2) database to declare the model.
Flask Flask-SQLAlchemy Relationships: One to Many In order to achieve that we place a Foreign key on the child referencing the parent that is from our example we place a foreign key on Post class to reference the User class. We then use relationship() on the parent which we access via our SQLAlchemy object db .
What is Flask-SQLAlchemy? Flask-SQLAlchemy is an extension for Flask that aims to simplify using SQLAlchemy with Flask by providing defaults and helpers to accomplish common tasks. One of the most sought after helpers being the handling of a database connection across the app.
What are binds? In SQLAlchemy speak a bind is something that can execute SQL statements and is usually a connection or engine. In Flask-SQLAlchemy binds are always engines that are created for you automatically behind the scenes. Each of these engines is then associated with a short key (the bind key).
Flask-SQLAlchemy 2.1 added support for a binds
parameter on the session which should do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With