Fastapi Blog Alembic
In this chapter, you will learn how to use Alembic to manage database schema changes, and understand the similarities and differences with Django Migration and Flask-Migrate.
* * *
## Why Do You Need a Migration Tool?
`Base.metadata.create_all()` also has a fatal flaw: it only creates tables if they don't exist, and changes to existing table structures won't be automatically synchronized.
Alembic is the official migration tool for SQLAlchemy. Django's `makemigrations/migrate` and Flask's Flask-Migrate are fundamentally based on Alembic's design.
* * *
## Installation and Initialization
(venv) $ pip install alembic (venv) $ alembic init alembic Creating directory alembic/... done
The generated directory structure:
alembic/βββ versions/ # Migration script directoryβββ env.py # Migration environment configuration (needs manual modification!)βββ script.py.mako # Migration script template alembic.ini # Alembic configuration file
* * *
## Configure env.py to Connect to Your Models
This is a critical stepβAlembic doesn't know where your SQLAlchemy models are by default.
## Example
# File path: alembic/env.py (modify key parts)
import sys
from pathlib import Path
# Add project root to sys.path (ensure your own modules can be imported)
sys.path.insert(0,str(Path( __file__ ).resolve().parent.parent))
from database import Base, engine
from models import Category, Post # Import all models to ensure Base.metadata contains them
# target_metadata must be set to the model's metadata
target_metadata = Base.metadata
Also modify the database connection in `alembic.ini`:
# File path: alembic.ini sqlalchemy.url = sqlite:///./blog.db
* * *
## The Three Steps of Migration
| Step | Command | Function | Django Equivalent |
| --- | --- | --- | --- |
| Initialize | alembic init alembic | Create migration environment (only once) | β |
| Generate | alembic revision --autogenerate -m "description" | Detect model changes and generate migration script | makemigrations |
| Execute | alembic upgrade head | Execute all unapplied migrations | migrate |
### Generate and Execute Migration
(venv) $ alembic revision --autogenerate -m "Initialize Post and Category models" INFO [alembic.autogenerate] Detected added table 'categories' INFO [alembic.autogenerate] Detected added table 'posts'Generating alembic/versions/xxxx_initial.py ... done(venv) $ alembic upgrade head INFO [alembic.runtime.migration] Running upgrade -> xxxx, Initialization
* * *
## Practice: Add read_count Field
## Example
# File path: models.py, add to Post class
class Post(Base):
# ... existing fields ...
read_count = Column(Integer, default=0)# Read count
(venv) $ alembic revision --autogenerate -m "Post add read_count field"(venv) $ alembic upgrade head
### Rollback
(venv) $ alembic downgrade -1 # Rollback to previous version
> The `head` in `alembic upgrade head` represents the latest version. You can also specify a specific version number: `alembic upgrade xxxx` (version ID).
* * *
## Three Framework Migration Tools Comparison
| Operation | Django | FlaskοΌFlask-MigrateοΌ | FastAPIοΌAlembicοΌ |
| --- | --- | --- | --- |
| Initialize | Not needed | flask db init | alembic init alembic |
| Generate migration | makemigrations | flask db migrate -m "description" | alembic revision --autogenerate -m "description" |
| Execute migration | migrate | flask db upgrade | alembic upgrade head |
| Rollback | migrate app 0001 | flask db downgrade | alembic downgrade -1 |
| Automation level | Highest | Medium | Requires manual env.py configuration |
* * *
## Chapter Summary
In this chapter, you mastered the complete Alembic workflow: alembic init for initialization, configuring env.py to connect models, revision --autogenerate to generate migrations, upgrade head to execute, and downgrade to rollback.
Alembic requires more configuration steps than Django/Flask migration tools, but it is moreUnderlying and flexible.
> Next Chapter Preview: As articles increase, search and pagination are needed. The next chapter will implement keyword combined search and pagination based on offset/limit.
YouTip