Flask-Migrate

4.1.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

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.

view raw JSON →