0
0
Flaskframework~30 mins

Database migration in deployment in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Database migration in deployment with Flask
📖 Scenario: You are building a Flask web app that stores user data in a database. When you update your app, you need to change the database structure without losing existing data. This process is called database migration.In this project, you will set up a simple Flask app with a database, configure migration support, create a migration script, and apply the migration to update the database.
🎯 Goal: Build a Flask app that uses Flask-Migrate to handle database migrations during deployment. You will create the initial database, configure migration settings, generate a migration script, and apply it to update the database schema safely.
📋 What You'll Learn
Use Flask with SQLAlchemy for database handling
Use Flask-Migrate to manage database migrations
Create an initial User model with id and name fields
Add a new email field to the User model via migration
Apply migration commands programmatically in the app
💡 Why This Matters
🌍 Real World
Database migrations are essential when deploying updates to web apps that use databases. They help change the database structure safely without losing user data.
💼 Career
Knowing how to manage database migrations with Flask and Flask-Migrate is a key skill for backend developers working on web applications that evolve over time.
Progress0 / 4 steps
1
Set up Flask app and initial User model
Create a Flask app instance called app. Set up SQLAlchemy with db = SQLAlchemy(app). Define a User model with id as an integer primary key and name as a string column. Initialize the database with db.create_all().
Flask
Need a hint?

Remember to import Flask and SQLAlchemy. Set the database URI to a local SQLite file. Define the User model with id and name columns. Call db.create_all() inside the app context.

2
Configure Flask-Migrate for migration support
Import Migrate from flask_migrate. Create a migrate object with migrate = Migrate(app, db) to enable migration support in your Flask app.
Flask
Need a hint?

Import Migrate and create a migrate object passing app and db.

3
Add new email field to User model for migration
Modify the User model by adding a new column email as a string with max length 120 and allow null values. Do not remove existing fields.
Flask
Need a hint?

Add email = db.Column(db.String(120), nullable=True) inside the User model.

4
Apply migration commands programmatically
Import upgrade from flask_migrate. Inside the app context, call upgrade() to apply the migration and update the database schema with the new email column.
Flask
Need a hint?

Import upgrade and call it inside the app context to apply migrations.