Flask-Migrate
Flask-Migrate is an extension for Flask applications that streamlines database migrations using SQLAlchemy and Alembic. It integrates Alembic's powerful migration capabilities with the Flask command-line interface, providing version control for your database schema. The library sees regular maintenance, with minor releases addressing bugs and improvements, and major versions released to ensure compatibility with newer Flask and SQLAlchemy versions.
Warnings
- breaking Version 4.0.0 introduced significant changes, including compatibility updates for Flask-SQLAlchemy 3.x and automatically enabling `compare_type=True` and `render_as_batch=True` in Alembic by default. If you had custom Alembic configurations, especially for SQLite, you might need to review them.
- gotcha The `flask db` commands rely on the `FLASK_APP` environment variable being correctly set to point to your Flask application instance (e.g., `app.py`). If this variable is not set or points to the wrong file, the commands will fail with 'No such command 'db''.
- gotcha Alembic's autogenerate feature (used by `flask db migrate`) cannot detect all types of schema changes, such as table renames, column renames, changes to anonymously named constraints, or some index changes. The generated script is a best effort.
- gotcha SQLite has limited `ALTER TABLE` support. Operations like dropping or renaming columns directly are often not possible. Flask-Migrate (via Alembic) works around this using a 'batch mode' (`render_as_batch=True`) which copies data to a new table, drops the old, and renames the new.
- gotcha Defining Flask app, SQLAlchemy db, and Flask-Migrate in the same file as models can lead to circular import issues, especially in larger applications.
Install
-
pip install Flask-Migrate
Imports
- Migrate
from flask_migrate import Migrate
Quickstart
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# Set FLASK_APP environment variable if not already set
if not os.environ.get('FLASK_APP'):
os.environ['FLASK_APP'] = 'app.py' # Assuming this file is named app.py
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))
def __repr__(self):
return f'<User {self.name}>'
# To run this quickstart:
# 1. Save as app.py
# 2. In your terminal, ensure FLASK_APP is set (e.g., `export FLASK_APP=app.py` or `set FLASK_APP=app.py`)
# 3. Run `flask db init` (creates migrations folder)
# 4. Run `flask db migrate -m "Initial migration"` (creates migration script)
# 5. Run `flask db upgrade` (applies migration to database)
# 6. Now you can modify the User model, then repeat steps 4 and 5 to update your schema.