Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Flask-Migrate — Database Migrations

Flask-Migrate — Database Migrations

In this chapter you will learn to use Flask-Migrate to safely manage database schema changes and understand the correspondence with Django migrations.


Why can't you always use db.create_all()?

db.create_all() It has two fatal flaws:

Database migration is like Git for the database—each schema change generates a version file, supporting upgrades and rollbacks.

Flask-Migrate is a Flask extension of Alembic, designed specifically for SQLAlchemy.


Installation and Configuration



(venv) $ pip install flask-migrate

Example

File path: app.py

from

flask

import

Flask

from

flask_sqlalchemy

import

SQLAlchemy

from

flask_migrate

import

Migrate

app

=

Flask

(

name

)

app.

config

[

'SQLALCHEMY_DATABASE_URI'

]

=

'sqlite:///blog.db'

db

=

SQLAlchemy

(

app

)

migrate

=

Migrate

(

app

,

db

)

   

Bind app and db to Migrate


The three-step migration process

Step Command Purpose Compared with Django
Initialization flask db init Create the migrations/ directory (only once) —
Generation flask db migrate -m "description" Detect model changes and generate migration scripts makemigrations
Executing flask db upgrade Apply the migration script to the database migrate

Step 1: Initialize the Migration Directory



(venv) $ flask db init

Creating directory migrations/...  done

After running it, a migrations/ directory is generated (similar to Git's .git directory); it only needs to be done once.

Step 2: Generate a Migration File



(venv) $ flask db migrate -m "初始化 Post 和 Category 模型"

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.

Generating migrations/versions/xxxx_initial.py ... done

If you have not made any model changes yet, you can run this command directly on the existing models.

Step 3: Run the Migration



(venv) $ flask db upgrade

INFO  [alembic.runtime.migration] Running upgrade  -> xxxx, 初始化


Hands-on: Adding a Field to the Post Model

Suppose a product requirement changes and you need to add a view counter to articles.

Example

File path: add to the Post class in models.py

class

Post

(

db.

Model

)

:

   

... existing fields ...

    read_count

=

db.

Column

(

db.

Integer

,

default

=

0

)

 

New: view count

After modifying the model, run the migration:



(venv) $ flask db migrate -m "Post 模型新增 read_count 字段"

(venv) $ flask db upgrade

Now the posts table in the database automatically gains a read_count column, and existing data is unaffected.

View Migration History

Check which version the current database is at:



(venv) $ flask db current

View all migration history:



(venv) $ flask db history


Roll Back a Migration

Migrations can be undone:



(venv) $ flask db downgrade   # 回退到上一个版本

This deletes the read_count column, undoing all changes from the last migration.

Not all operations can be automatically rolled back (e.g., dropping a column in SQLite). Before rolling back, first confirm flask db current Check the current version to ensure you know what you are reverting. Always back up data before rolling back in production.


Flask-Migrate vs Django Migration Comparison

Operation Flask(Flask-Migrate) Django
Initialization flask db init Not needed (the project ships with a migrations directory)
Generate migration flask db migrate -m "description" python manage.py makemigrations
Run migration flask db upgrade python manage.py migrate
Rollback flask db downgrade python manage.py migrate app 0001
View history flask db history python manage.py showmigrations
Degree of Automation Requires initialization; detection depends on Alembic Fully automatic, no extra configuration needed

Django's migration system is more automated and integrated; Flask achieves the same level of capability through Flask-Migrate.


Chapter Summary

In this chapter you mastered the complete Flask-Migrate workflow: flask db init to initialize, flask db migrate to generate a migration script, flask db upgrade to run the migration, and flask db downgrade to roll back.

From now on, every modification to models.py follows this three-step workflow, so database schema changes always have a traceable history.