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
Flask Database Operations: A Beginner's Guide to SQLAlchemy ORM

ORM solves the maintenance difficulties of directly writing SQL in web development by simplifying operations through mapping database table structures with Python objects. Flask + SQLAlchemy is a commonly used combination, and you need to install `flask` and `flask-sqlalchemy` first. During initialization, configure the SQLite database path (e.g., `sqlite:///mydatabase.db`) and disable modification tracking. Define model classes (such as User) that inherit from `db.Model`, with class attributes corresponding to table fields (including primary keys and constraints). Use `db.create_all()` to automatically generate the tables. Core operations are session-based (`db.session`): creation (`add` + `commit`), reading (`query.all()`/`filter_by()`/`get()`), updating (modify attributes + `commit`), and deletion (`delete` + `commit`). After mastering this process, you can extend to databases like MySQL and explore advanced features such as relationship models.

Read More