Skip to main content

Setting up Flask Migrate with existing SQL database / Resetting Flask Migrations

Flask Migrate allows to manage SQLAlchemy database migrations for Flask applications using Alembic. One of the common user-scenaio is that you have an existing database being used in the Flask Application. If you would like to integrate Flask-Migrate, this post will help you to start with the setup. Other user-scenario that I have seen is that once you integrate Flask-Migrate, some times people accidentally delete the migrations folder or would like to reset the migrations, the same steps can be followed.

Let's get started. First step is to make sure that the flask-migrate is installed and included in your flask project.

from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, redirect, url_for
from flask_migrate import Migrate
import os

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

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'database.db')
app.config['SECRET_KEY'] = 'bfd1d3721'

db = SQLAlchemy(app)
migrate = Migrate(app, db) # Setup of Flask-Migrate

If you are resetting the migrations, you need to delete the "alembic_version" table from the database. This is only valid if you are already using flask-migrate and accidentally deleted the migrations folder. Once you perform this operation, the setup is like that you are integrating flask migrate into an existing database.

Step 1 : Initialize the migrations using the following command :-

flask db init 

Step 2 : Create a new database temporarily for migrations. If you are using SQLite, you can use in-memory temporary database, for other back-end, create the database accordingly.

In my case, I am simply creating a new database "database_temp.db" using Flask configuration.

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'database_temp.db')

Once done, execute the following command :-

flask db migrate

Step 3 : Now revert to your existing database in Flask configuration and you can delete the temporary database if you have created in database server.

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'database.db')

Step 4 : Run the following command :-

flask db stamp head

Step 5 : Finally run the db upgrade command to apply the migrations with the following command :-

flask db upgrade


Comments