Last modified: Jun 01, 2025 By Alexander Williams

Install Flask-Migrate in Python

Flask-Migrate is a Python extension for handling database migrations in Flask applications. It uses Alembic under the hood.

Migrations help manage changes to your database schema over time. This is useful when working with SQL databases like PostgreSQL or MySQL.

Prerequisites

Before installing Flask-Migrate, you need:

  • Python 3.6 or higher
  • Flask installed
  • A Flask-SQLAlchemy setup

If you need to install Flask first, check our guide on How to Install Flask-Login in Python for similar setup steps.

Installation Steps

Follow these steps to install Flask-Migrate:

1. Create a Virtual Environment

It's good practice to work in a virtual environment:


python -m venv myenv
source myenv/bin/activate  # On Windows use myenv\Scripts\activate

2. Install Flask-Migrate

Use pip to install the package:


pip install flask-migrate

This will also install Alembic as a dependency.

3. Configure Your Flask Application

Add Flask-Migrate to your Flask app:


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

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)  # Initialize Flask-Migrate

Using Flask-Migrate

After installation, you can use these commands:

Initialize Migrations

First, create the migrations directory:


flask db init

This creates a migrations folder in your project.

Create a Migration

Generate a migration after changing your models:


flask db migrate -m "Initial migration"

Apply Migrations

Run this to update your database:


flask db upgrade

Example Project

Here's a complete example with a simple User model:


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

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

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

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))
    
if __name__ == '__main__':
    app.run()

After creating this file, run the migration commands shown earlier.

Troubleshooting

If you encounter issues:

  • Make sure Flask-SQLAlchemy is properly configured
  • Check your database connection string
  • Verify all packages are installed

For internationalization needs, you might also find our Install Babel for Python Internationalization guide helpful.

Conclusion

Flask-Migrate simplifies database migrations in Flask applications. It's an essential tool when working with databases in Flask.

The installation process is straightforward. Just remember to initialize and run migrations after model changes.

For other Flask extensions, check our guide on Install Flask-Mail in Python.