0
0
Flaskframework~5 mins

Database migration in deployment in Flask

Choose your learning style9 modes available
Introduction

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.

When you add a new feature that needs new tables or columns in the database.
When you fix or change how data is stored without losing existing data.
When you move your app to a new server or environment and need the database set up.
When you want to keep track of database changes over time in a team project.
Syntax
Flask
flask db init
flask db migrate -m "message"
flask db upgrade

flask db init creates migration setup files once per project.

flask db migrate creates a migration script based on model changes.

Examples
Run this once to set up migration files in your Flask project.
Flask
flask db init
This creates a migration script describing the change to add an email column.
Flask
flask db migrate -m "Add user email column"
This applies the migration to update the database schema.
Flask
flask db upgrade
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.