SQLAlchemy database migrations for Flask applications using Alembic.
Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. It provides both a programmatic Python API and command-line interface through Flask CLI, enabling developers to manage database schema changes, version control database structure, and handle migrations across different environments seamlessly.
pip install Flask-Migratefrom flask_migrate import MigrateFor using individual migration functions:
from flask_migrate import init, migrate, upgrade, downgrade, revisionFor CLI integration (automatic with Flask 0.11+):
# CLI commands automatically registered as 'flask db' when extension is importedfrom 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)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
# Command line usage:
# flask db init # Initialize migration repository
# flask db migrate # Generate migration script
# flask db upgrade # Apply migrations to databaseFlask-Migrate bridges Flask applications with Alembic's migration capabilities through several key components:
flask db namespaceMain Flask extension class for initializing and configuring the migration system with Flask applications and SQLAlchemy databases.
class Migrate:
def __init__(self, app=None, db=None, directory='migrations', **kwargs): ...
def init_app(self, app, db=None, directory=None, **kwargs): ...
def configure(self, f): ...
def call_configure_callbacks(self, config): ...
def get_config(self, directory=None, x_arg=None, opts=None): ...Core database migration operations for creating, generating, and applying schema changes with full version control and rollback capabilities.
def init(directory=None, multidb=False, template=None, package=False): ...
def revision(directory=None, message=None, autogenerate=False, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None): ...
def migrate(directory=None, message=None, sql=False, head='head', splice=False, branch_label=None, version_path=None, rev_id=None, x_arg=None): ...
def upgrade(directory=None, revision='head', sql=False, tag=None, x_arg=None): ...
def downgrade(directory=None, revision='-1', sql=False, tag=None, x_arg=None): ...Database migration history, status, and inspection operations for understanding current migration state and tracking changes over time.
def current(directory=None, verbose=False): ...
def history(directory=None, rev_range=None, verbose=False, indicate_current=False): ...
def show(directory=None, revision='head'): ...
def heads(directory=None, verbose=False, resolve_dependencies=False): ...
def branches(directory=None, verbose=False): ...
def stamp(directory=None, revision='head', sql=False, tag=None): ...Advanced migration operations for complex scenarios including merging branches, editing revisions, and template management.
def merge(directory=None, revisions='', message=None, branch_label=None, rev_id=None): ...
def edit(directory=None, revision='current'): ...
def list_templates(): ...class Config:
"""Custom Alembic configuration class with template directory support."""
def __init__(self, *args, template_directory=None, **kwargs): ...
def get_template_directory(self): ...
class _MigrateConfig:
"""Internal configuration wrapper for Flask app integration."""
def __init__(self, migrate, db, **kwargs): ...
@property
def metadata(self): ...
def catch_errors(f):
"""Decorator that catches CommandError and RuntimeError, logs them and exits."""
...alembic_version: tuple
"""Parsed Alembic version as tuple of integers (e.g., (1, 4, 3))."""
log: logging.Logger
"""Module logger instance for Flask-Migrate operations."""All migration functions are decorated with @catch_errors which catches alembic.util.CommandError and RuntimeError, logs the error message, and exits with code 1. This ensures consistent error handling across all migration operations.
Flask-Migrate includes built-in templates for different database configurations:
Custom templates can be specified using absolute paths or by placing them in the templates directory.
tessl i tessl/pypi-flask-migrate@3.1.0