Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using different binds in the same class in Flask-SQLAlchemy

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.

like image 931
miscsubbin Avatar asked Jun 10 '13 13:06

miscsubbin


People also ask

How do I use two databases on a Flask?

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.

How do you create a one to many relationship in Flask-SQLAlchemy?

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 .

Is Flask-SQLAlchemy the same as SQLAlchemy?

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 is Sqlalchemy_binds?

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


1 Answers

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

like image 97
Jeff Widman Avatar answered Oct 17 '22 09:10

Jeff Widman