Flask Blog Migrate
In this chapter you will learn to use Flask-Migrate to safely manage database schema changes and understand the corresponding relationship with Django migrations.
* * *
## Why can't we always use db.create_all()?
`db.create_all()` has two fatal flaws:
* It only creates tables if they don't exist. When modifying models (such as adding new fields), existing tables will not be updated
* It doesn't preserve change history. Cannot rollback to previous database states
Database migration is like Git for databases β each schema change generates a version file, supporting upgrades and rollbacks.
Flask-Migrate is a Flask extension for 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 Steps of Migration
| Step | Command | Function | Django Equivalent |
| --- | --- | --- | --- |
| Initialize | flask db init | Create migrations/ directory (only once) | β |
| Generate | flask db migrate -m "description" | Detect model changes, generate migration script | makemigrations |
| Execute | flask db upgrade | Apply migration script to database | migrate |
### Step 1: Initialize Migration Directory
(venv) $ flask db init Creating directory migrations/... done
After execution, the `migrations/` directory is created (similar to Git's .git directory), only needs to be executed once.
### Step 2: Generate Migration File
(venv) $ flask db migrate -m "Initialize Post and Category models" INFO [alembic.runtime.migration] Context impl SQLiteImpl.Generating migrations/versions/xxxx_initial.py ... done
If you haven't made any model changes yet, you can directly run this command on existing models.
### Step 3: Execute Migration
(venv) $ flask db upgrade INFO [alembic.runtime.migration] Running upgrade -> xxxx, initialize
* * *
## Practical: Add a New Field to Post Model
Assume product requirements change and you need to add a read count to articles.
## Example
# Add to Post class in models.py
class Post(db.Model):
# ... existing fields ...
read_count = db.Column(db.Integer, default=0)# New: read count
After modifying the model, execute migration:
(venv) $ flask db migrate -m "Add read_count field to Post model"(venv) $ flask db upgrade
Now the `posts` table in the database automatically has the `read_count` column added, and existing data is not affected.
### View Migration History
View which version the current database is at:
(venv) $ flask db current
View all migration history:
(venv) $ flask db history
* * *
## Rollback Migration
Migrations can be reverted:
(venv) $ flask db downgrade # Rollback to previous version
This will delete the `read_count` column and revert all changes from the last migration.
> Not all operations can be automatically rolled back (such as deleting columns in SQLite). Before rolling back, first confirm with `flask db current` to view the current version, ensure you know what you are reverting. Be sure to backup data before rolling back in production environment.
* * *
## Flask-Migrate vs Django Migration Comparison
| Operation | Flask (Flask-Migrate) | Django |
| --- | --- | --- |
| Initialize | flask db init | Not needed (project has migrations directory built-in) |
| Generate migration | flask db migrate -m "description" | python manage.py makemigrations |
| Execute 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 |
| Automation level | Requires initialization, depends on Alembic | Fully automated, no additional 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 process: `flask db init` for initialization, `flask db migrate` to generate migration scripts, `flask db upgrade` to execute migrations, and `flask db downgrade` to rollback.
From now on, every time you modify models.py, follow this three-step process, and database schema changes will always have a traceable history.
YouTip