[파이썬] Flask-SQLAlchemy 데이터베이스 마이그레이션

Flask-SQLAlchemy is a popular extension for Flask that simplifies the process of creating and interacting with databases. In this blog post, we will focus on database migration using Flask-SQLAlchemy. Database migration is the process of updating a database schema while preserving existing data.

Why Use Database Migration?

When developing an application, it is common to make changes to the database schema over time. This could involve adding new tables, modifying existing tables, or even altering column types. Without a proper migration strategy, these changes can become challenging to manage and implement.

Database migration allows you to apply these schema changes incrementally and in a controlled manner. It ensures that you can update your database schema without losing any data or disrupting the application’s functionality.

Flask-Migrate for Database Migration

Flask-Migrate is a Flask extension that provides a simple and efficient way to handle database migration using Flask-SQLAlchemy. It is built on top of Alembic, a database migration framework for SQLAlchemy.

To get started, let’s install the necessary packages:

$ pip install Flask-Migrate

Once installed, we need to initialize Flask-Migrate in our Flask application. Open app.py and add the following code:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)

Here, we import the necessary Flask-Migrate classes and create instances of them. We also set the SQLite database URI as an example, but you can use any other supported database.

Creating Database Migrations

Once Flask-Migrate is set up, we can start creating database migrations. The flask db command allows us to generate and apply migrations.

To create a migration, open your terminal and navigate to your project directory. Then run the following command:

$ flask db init

This command initializes the migration environment and creates a new migrations directory if it doesn’t already exist.

To generate an initial migration, run the following command:

$ flask db migrate -m "Initial migration"

This command creates an auto-generated migration script file in the migrations directory. The -m flag allows us to add a short description for the migration.

To apply the migration and update the database schema, run the following command:

$ flask db upgrade

This command applies any pending migrations and updates the database schema accordingly.

Modifying the Database Schema

To demonstrate how database migration works, let’s say we need to add a new table called users to our application.

In your models.py file, add the following code:

from app import db

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

To generate a migration for this change, run the following command:

$ flask db migrate -m "Adding users table"

This command will generate a migration script that adds the users table to the database.

To apply the migration, run the following command:

$ flask db upgrade

This command will update the database schema and create the users table.

Conclusion

In this blog post, we’ve introduced Flask-SQLAlchemy and its integration with Flask-Migrate for database migration. We’ve covered the basics of setting up Flask-Migrate, generating and applying migrations, and modifying the database schema in a controlled manner.

Database migration is an essential process when working with evolving database schemas. Flask-SQLAlchemy and Flask-Migrate provide a powerful and user-friendly framework to manage database changes effectively.

By using these tools, you can ensure that your database remains up-to-date with the evolving needs of your application while maintaining data integrity.