FastAPI Backend Development Bootcamp · 课时

使用 Alembic 进行数据库迁移

使用 Alembic 安全地演进 SQLAlchemy 模式:初始化迁移、自动生成修订版本,并在 FastAPI 项目中应用或回滚变更。

第 4 / 4 课13 个步骤

使用 Alembic 进行数据库迁移 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Migrations

Your database schema changes as your app grows: new columns, tables, and indexes. Migrations are versioned, repeatable scripts that evolve the schema without losing data. Alembic is the standard tool for SQLAlchemy.

create_all Is Not Enough

Base.metadata.create_all() creates missing tables but never alters existing ones. It cannot add a column to a populated table or track history. Production needs real migrations.

Installing and Initializing

Install Alembic and scaffold its folder. This creates an alembic/ directory and alembic.ini.

pip install alembic
alembic init alembic

Pointing Alembic at Your Models

In alembic/env.py, set target_metadata to your SQLAlchemy Base.metadata so autogenerate can compare models to the live schema.

from app.database import Base
from app import models  # ensure models are imported

target_metadata = Base.metadata

Setting the Database URL

Configure the connection string. Reading it from an env var keeps secrets out of source control.

import os
config.set_main_option('sqlalchemy.url', os.environ['DATABASE_URL'])

Autogenerating a Revision

Alembic compares your models to the database and writes a migration script with the differences.

alembic revision --autogenerate -m 'add email to users'

Anatomy of a Migration

Each script has upgrade() and downgrade(). Upgrade applies the change; downgrade reverses it. Always review autogenerated code before running it.

def upgrade():
    op.add_column('users', sa.Column('email', sa.String(), nullable=True))

def downgrade():
    op.drop_column('users', 'email')

Applying Migrations

Run upgrade head to apply all pending migrations up to the latest revision.

alembic upgrade head

Rolling Back

Step back one revision with downgrade -1, or to a specific revision id. Rollbacks are why writing accurate downgrade() matters.

alembic downgrade -1

Revision Chain Mental Model

Migrations form a linked list: each revision records its down_revision. Alembic walks the chain to know what to apply. Here is the idea in plain Python.

revisions = [
    {'id': 'a1', 'down': None},
    {'id': 'b2', 'down': 'a1'},
    {'id': 'c3', 'down': 'b2'},
]
order = []
cur = 'c3'
by_id = {r['id']: r for r in revisions}
while cur:
    order.append(cur)
    cur = by_id[cur]['down']
print(list(reversed(order)))

Migration Best Practices

Keep migrations safe:

  • Review autogenerated scripts; they miss some changes (e.g. column renames).
  • Run migrations in CI/CD before deploying code.
  • Make additive changes first, remove old columns in a later release.
  • Never edit an already-applied migration; create a new one.

Quick Check

Why is Base.metadata.create_all() insufficient for evolving a production schema?

Recap

You added safe schema evolution:

  • Initialized Alembic and wired it to your models and DB URL.
  • Autogenerated revisions with upgrade() / downgrade().
  • Applied with upgrade head and reverted with downgrade.
  • Followed best practices for reviewing and sequencing migrations.
免费开始

用 AI 导师学习 FastAPI Backend Development Bootcamp — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
21
课程
84

常见问题解答

「使用 Alembic 进行数据库迁移」课时是免费的吗?

是的 — 「使用 Alembic 进行数据库迁移」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「使用 Alembic 进行数据库迁移」这节课中我会学到什么?

使用 Alembic 安全地演进 SQLAlchemy 模式:初始化迁移、自动生成修订版本,并在 FastAPI 项目中应用或回滚变更。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「使用 Alembic 进行数据库迁移」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. SQLAlchemy ORM 基础
  2. 将 FastAPI 连接到 PostgreSQL
  3. 使用 SQLAlchemy 执行 CRUD 操作
  4. 使用 Alembic 进行数据库迁移
← 返回 FastAPI Backend Development Bootcamp