Registry / web-framework / flask-migrate

flask-migrate

JSON →
library4.1.0pypypi✓ verified 26d ago

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.

pip install Flask-Migrate
INSTALL
IMPORT
SIG · FLASK-MIGRATE
F
flask-migrate
web-frameworkpythonv4.1.0
Install
4.4s avg
Import
1368ms
Disk
50MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.388s · 51.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 4.4s · import 1.348s · 49MB
50MB installed
● package 50MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Migrate
from flask_migrate import Migrate

This example demonstrates the basic setup of Flask-Migrate with a Flask application and a SQLAlchemy model. It outlines the common commands to initialize a migration repository, create an initial migration script, and apply database changes.

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.
flask --version
Debug
Known issues
breakingVersion 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.
fix
Review your application's `app.config['SQLALCHEMY_DATABASE_URI']` and any custom Alembic configurations. For SQLite, `render_as_batch=True` is now default, which should help with `ALTER TABLE` operations, but test thoroughly.
affects: >=4.0.0
gotchaThe `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''.
fix
Before running any `flask db` command, ensure `FLASK_APP` is set in your environment: `export FLASK_APP=your_app_file.py` (Linux/macOS) or `set FLASK_APP=your_app_file.py` (Windows).
affects: All versions
gotchaAlembic'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.
fix
Always review the generated migration script (`migrations/versions/*.py`) after running `flask db migrate`. Manually edit the `upgrade()` and `downgrade()` functions to correctly reflect any undetected changes before running `flask db upgrade`.
affects: All versions
gotchaSQLite 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.
fix
For versions < 4.0.0, explicitly set `render_as_batch=True` when initializing Migrate: `migrate = Migrate(app, db, render_as_batch=True)`. For all versions, be aware that complex SQLite schema changes might still require manual intervention in the migration script.
affects: All versions when using SQLite. Default behavior changed in 4.0.0.
gotchaDefining Flask app, SQLAlchemy db, and Flask-Migrate in the same file as models can lead to circular import issues, especially in larger applications.
fix
Structure your application to separate concerns: e.g., `app.py` for Flask app and `Migrate` initialization, `models.py` for SQLAlchemy models, and `config.py` for configuration. Import models into `app.py` *after* `db` is initialized to ensure they are registered with SQLAlchemy.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'flask_migrate'
The `flask_migrate` package is not installed in the current Python environment or the environment where the Flask application is being run.
fix
Ensure Flask-Migrate is installed using pip: `pip install Flask-Migrate`. If using a virtual environment, make sure it's activated before installation.
Error: No such command 'db'
The Flask `db` command group, provided by Flask-Migrate, is not registered with the Flask application. This often happens when `Migrate` is not properly initialized with the Flask app and SQLAlchemy `db` object, or when the `FLASK_APP` environment variable is not correctly set to point to your application instance.
fix
Ensure `Migrate` is initialized correctly in your Flask application (e.g., `migrate = Migrate(app, db)`). Also, verify that the `FLASK_APP` environment variable is set to the correct entry point for your Flask application (e.g., `export FLASK_APP=your_app_name.py`).
RuntimeError: Working outside of application context.
This error occurs when `flask-migrate` or `SQLAlchemy` operations requiring an active Flask application context are called outside of one, typically in scripts or at the module level before the application context has been pushed.
fix
Ensure operations that require the application context (like initializing `Migrate` or `SQLAlchemy`) are done within an active application context. For CLI commands, ensure `FLASK_APP` is set. For programmatic access outside of a request, use `with app.app_context():` to establish a context.
Flask-Migrate not detecting model changes (generates empty migration script)
Alembic (used by Flask-Migrate) may not detect changes to your SQLAlchemy models if the models are not properly imported into the environment where migrations are generated (e.g., `migrations/env.py`), or if the database schema already matches the models.
fix
Ensure all your SQLAlchemy models are imported within your `env.py` file or in a module that `env.py` imports. Sometimes, simply adding `import app.models` (or your specific models package) in `env.py` after `target_metadata` is defined can resolve this. Also, verify that changes are truly present and not already applied to the database by manually checking the database schema.
AttributeError: can't set attribute
This error often indicates an incompatibility between Flask-Migrate and the installed version of SQLAlchemy, or sometimes an issue with how models are defined (e.g., trying to set a read-only attribute). Specific cases like 'AttributeError: module 'sqlalchemy' has no attribute 'Variant'' are common with older SQLAlchemy versions not compatible with newer Flask-Migrate.
fix
Check the compatibility matrix for Flask-Migrate and SQLAlchemy versions. Upgrading or downgrading SQLAlchemy to a compatible version often resolves this. For instance, `pip install 'SQLAlchemy<1.4'` was a common fix for certain `AttributeError` issues. Review your model definitions for any unusual attribute assignments.
Upgrade
Version history
4.1.0latest on PyPI · released Jan 10, 2025
Audit
Dependencies
FlaskrequiredCore web framework integration.
Flask-SQLAlchemyrequiredORM integration for database interactions.
AlembicrequiredUnderlying database migration tool, configured by Flask-Migrate.
Agent activity
13 hits · last 30 days
node
10
Resources
flask-migrate — pip install flask-migrate · libregistry