Beginner-Friendly: Flask-Migrate Database Migration Tutorial

### Why Database Migration is Needed? As database structures evolve with changing requirements during development, manual modifications risk data loss or version chaos. Migration tools enable safe structural changes while preserving data, akin to "database version control." ### What is Flask-Migrate? It is a Flask extension built on Alembic, designed to manage database schema changes in conjunction with SQLAlchemy. It automatically generates migration scripts, eliminating the need for manual SQL writing. ### Installation and Initialization Install dependencies: `pip install flask flask-sqlalchemy flask-migrate`. Initialize: Set the `FLASK_APP` environment variable, then run `flask db init` to generate the `migrations` folder and define models (e.g., a `User` table). ### Core Migration Commands 1. **Initialize Migration Environment** (first time): `flask db init` generates the `migrations` folder. 2. **Generate Migration Script**: After modifying models, run `flask db migrate -m "description of changes"` to create the SQL script. 3. **Apply Migration**: Execute `flask db upgrade` to apply the changes. ### Practical Workflow 1. Modify the model (e.g., add an `age` field); 2. Generate the script: `

Read More