Handle Multiple Database tables in one Single Flask API Application
from flask_script import Managerfrom flask_sqlalchemy import SQLAlchemyapp=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://username:password@localhost/alchemy'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
app.config['SQLALCHEMY_ECHO']=True
app.config['SQLALCHEMY_BINDS']={'two':'postgresql://username:password@localhost/seconddb',
'three':'postgresql://username:password@localhost/thirddb'}db=SQLAlchemy(app)
migrate=Migrate(app,db)
manager=Manager(app)
manager.add_command('multidb',MigrateCommand)
class firstdbtable(db.Model):
id=db.Column(db.Integer,primary_key=True)
class seconddbtable(db.Model):
__bind_key__='two'
id = db.Column(db.Integer, primary_key=True)
class thirddbtable(db.Model):
__bind_key__='three'
id = db.Column(db.Integer, primary_key=True)
if __name__=='__main__':
manager.run()
We can use multiple tables to represent our Models.The tables that we are using are stored in different databases under one single instance of postgres SQL server.The username and password will be as configured in your server.
Please use the username and password as per your system.
app.config['SQLALCHEMY_BINDS']={'two':'postgresql://username:password@localhost/seconddb',
'three':'postgresql://username:password@localhost/thirddb'}
The first or the default database will always be considered as per :- [‘SQLALCHEMY_DATABASE_URI’].The key ‘two’ represent the path of the seconddb database and the key ‘three’ represents the third database.
Now,we need to indicate in our Model class to create the table in these databases by specifying the __bind_key__ attribute in the appropriate Model Class.
class seconddbtable(db.Model):
__bind_key__='two'
id = db.Column(db.Integer, primary_key=True)
Similarly,We connect the third model class to the third database tables by specifying __bind_key__=’three’.