0
0
Flaskframework~30 mins

Database migrations with Flask-Migrate - Mini Project: Build & Apply

Choose your learning style9 modes available
Database migrations with Flask-Migrate
📖 Scenario: You are building a simple Flask web app to manage a list of books. You want to keep your database structure organized and easy to update as your app grows.
🎯 Goal: Learn how to set up Flask-Migrate to handle database migrations. You will create the initial database model, configure Flask-Migrate, generate a migration script, and apply it to update the database.
📋 What You'll Learn
Create a Flask app with SQLAlchemy and a Book model
Configure Flask-Migrate with the Flask app and database
Generate an initial migration script for the Book model
Apply the migration to create the books table in the database
💡 Why This Matters
🌍 Real World
Database migrations help developers update database structures without losing data. This is essential when apps grow and change.
💼 Career
Knowing Flask-Migrate is important for backend developers working with Flask apps to maintain and evolve databases safely.
Progress0 / 4 steps
1
Create the Flask app and Book model
Create a Flask app instance called app. Set up SQLAlchemy with db = SQLAlchemy(app). Define a Book model with id as an integer primary key and title as a string column.
Flask
Need a hint?

Remember to import Flask and SQLAlchemy. Set the database URI to use SQLite file books.db.

2
Configure Flask-Migrate
Import Migrate from flask_migrate. Create a migrate object with migrate = Migrate(app, db) to link Flask-Migrate with your app and database.
Flask
Need a hint?

Import Migrate and create the migrate object after setting up db.

3
Generate the initial migration script
Use the Flask CLI command flask db init to create the migrations folder. Then run flask db migrate -m "Initial migration" to generate the migration script for the Book model.
Flask
Need a hint?

These commands are run in the terminal, not in Python code. They create migration files for your database changes.

4
Apply the migration to update the database
Run the Flask CLI command flask db upgrade in your terminal to apply the migration and create the books table in the database.
Flask
Need a hint?

This command applies the migration changes to your database. Run it in the terminal.