Flask · Lesson 14 of 15
Migrations and Schema Changes
Expand/contract migrations, data migrations and zero-downtime habits.
- Advanced
- 14 min read
- 3 objectives
Before this lessonLesson 13: The Flask CLI and Shell
What you will learn
- Add a nullable column
- Backfill data
- Drop a column safely
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Alembic (via Flask-Migrate) is how schema changes reach production. The unsafe habit is adding a non-null column with no default to a live table.
Expand, then contract
- Expand: add a nullable column, deploy code that writes to both old and new, backfill.
- Migrate reads: deploy code that reads the new column.
- Contract: drop the old column in a later release.
flask db migrate -m "add posts.excerpt nullable"
# review the generated file, then:
flask db upgradeA data migration
def upgrade():
op.add_column("post", sa.Column("excerpt", sa.String(200), nullable=True))
conn = op.get_bind()
conn.execute(sa.text("UPDATE post SET excerpt = substr(body, 1, 160) WHERE excerpt IS NULL"))
def downgrade():
op.drop_column("post", "excerpt")