2

I am using Flask Application with flask-migrate. I have initialized the app with single database but now the requirement is to add multiple databases.

Here are the steps that I followed with the below code :-

from flask import Flask 
from flask_sqlalchemy import SQLAlchemy 
import os
from flask_migrate import Migrate

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'database1.db')

"""
app.config['SQLALCHEMY_BINDS'] = {
        'database2' : 'sqlite:///' + os.path.join(basedir, 'database2.db')
    }
"""

db = SQLAlchemy(app)
migrate = Migrate(app, db)

class Table1(db.Model):
    id = db.Column(db.Integer, primary_key=True)

"""
class Table2(db.Model):
    __bind_key__ = 'database2'
    id = db.Column(db.Integer, primary_key=True)
"""

@app.route('/add1')
def index():
    item = Table1(id=2)
    db.session.add(item)
    db.session.commit()
    return 'Added value'

"""
@app.route('/add2')
def index2():
    item = Table2(id=2)
    db.session.add(item)
    db.session.commit()
    return 'Added table2 value'
"""
    
if __name__ == '__main__':
    app.run(debug=True)

Initialized the code as below

flask db init
flask db migrate
flask db upgrade

Visit http://127.0.0.1:5000/add1 to add to database1

Now uncomment the code so that the database2 can be added. On running flask db init again with --multidb switch, an error is reported.

(venv) bash-4.1$ flask db init --multidb
Error: Directory migrations already exists and is not empty

How can I convert an existing flask project with migrations to support multiple databases? Also, these multiple databases will evolve over the time i.e. I might have to add more databases. So, what is the best way to keep on adding more databases?

EDIT

One solution, I find is to remove the alembic_version table from existing database, remove the migrations folder and then do db init --multidb. I am okay resetting the migrations but want to know if this is the only solution?

sarbjit
  • 3,786
  • 9
  • 38
  • 60

0 Answers0