Database migration helps you update your app's database structure safely when you change your code. It keeps your data and app working well together.
Database migration in deployment in Flask
flask db init
flask db migrate -m "message"
flask db upgradeflask db init creates migration setup files once per project.
flask db migrate creates a migration script based on model changes.
flask db init
flask db migrate -m "Add user email column"flask db upgrade
This Flask app uses Flask-Migrate to handle database changes. Initially, the User model has only a username. Later, we add an email column. We create migration scripts and apply them to update the database without losing data.
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) migrate = Migrate(app, db) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, nullable=False) # After adding this new column, run: # flask db migrate -m "Add email to User" # flask db upgrade # Updated User model with new email column class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=True) if __name__ == '__main__': app.run(debug=True)
Always back up your database before running migrations in production.
Use descriptive messages in flask db migrate -m to track changes clearly.
Test migrations in a development environment before applying them live.
Database migration updates your database structure safely as your app changes.
Use Flask-Migrate commands: init, migrate, and upgrade.
This keeps your data safe and your app working smoothly during updates.