Python & FastAPI•Part 5: ORMs, Databases & Background Workers (56 - 65)
Alembic Migration Best Practices:
In Simple Words:
- Always inspect autogenerated migrations before applying.
- Use
op.batch_alter_tablefor SQLite compatibility. - Ensure all new columns have default values or are nullable for zero downtime.
python
# Alembic migration script (versions/xxxx_add_status.py):
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('orders', sa.Column('status', sa.String(20), server_default='pending'))
def downgrade():
op.drop_column('orders', 'status')