Mastering Flask Migrations: A Comprehensive Tutorial
In the dynamic world of web development, it's crucial to manage changes to your database schema efficiently. Flask-Migrate, an extension for Flask, allows you to handle database migrations with ease. In this tutorial, we'll guide you through the process of using Flask-Migrate to manage your database schema changes.
Prerequisites
Before we dive into the tutorial, ensure you have the following prerequisites:
- Python 3.6 or later
- Flask 1.1 or later
- SQLAlchemy 1.3 or later
- Flask-Migrate 2.5 or later
Setting Up Your Flask Application
First, let's set up a basic Flask application with SQLAlchemy as the Object-Relational Mapping (ORM) tool. We'll use Flask-Migrate to manage the database migrations.

Install the required packages:
pip install flask flask_sqlalchemy flask_migrate
Create a new file app.py and add the following code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
Defining Your Database Model
Let's define a simple User model for demonstration purposes.

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
Initializing Flask-Migrate
Now, let's initialize Flask-Migrate. Run the following command in your terminal:
export FLASK_APP=app.py
flask db init
This command creates a new migrations folder and sets up the necessary files.
Generating Migrations
Whenever you make changes to your models, you need to generate a new migration. Let's add a new column active to our User model.

active = db.Column(db.Boolean, default=False)
Generate a new migration with the following command:
flask db migrate -m "Add active column to User model"
The -m flag allows you to add a message describing the migration.
Upgrading and Downgrading Migrations
To apply the migration, use the upgrade command:
flask db upgrade
If you need to revert a migration, use the downgrade command:
flask db downgrade
Stamping and Revising Migrations
Sometimes, you might want to mark a specific version as the current one (stamping) or revise the migration history (revising).
| Command | Description |
|---|---|
flask db stamp |
Stamps the current version as the latest one. |
flask db revise -m "Revision message" |
Revises the migration history with the given message. |
Conclusion
In this tutorial, we've covered the basics of using Flask-Migrate to manage database migrations in your Flask applications. By following these steps, you can efficiently handle schema changes and keep your database in sync with your application's models.






















