1. Preparation
1. Install the necessary packages
First, make sure that Flask is installed along with Flask-SQLAlchemy (for database operations) and Flask-Migrate (for database migration). If it has not been installed, you can install it through the pip command:
pip install Flask Flask-SQLAlchemy Flask-Migrate
2. Configure the database
In Flask applications, you need to configure database connections. This is usually done in the application's configuration file, e.g.. The configuration content may include the database type (such as SQLite, MySQL, PostgreSQL, etc.), username, password, host address, port number, and database name.
class Config: # Example configuration, taking MySQL as an example SQLALCHEMY_DATABASE_URI = 'mysql://username:password@host:port/dbname' SQLALCHEMY_TRACK_MODIFICATIONS = False # Disable tracking of object modifications and send signals
Then, in the main file of the Flask application (e.g.) Import and apply this configuration.
3. Initialize SQLAlchemy and Migrate
In Flask applications, SQLAlchemy and Migrate need to be initialized. This is usually done in the main file of the application.
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate app = Flask(__name__) .from_object('') # Assume that the configuration file is named and the configuration class name is Config db = SQLAlchemy(app) migrate = Migrate(app, db)
2. Create a database migration
1. Define the model
In Flask applications, the model is usually defined inin the file. These models represent tables in the database and use SQLAlchemy's ORM (Object Relationship Mapping) function to define the fields and relationships of the table.
# from app import db class User(): id = (, primary_key=True) username = ((80), unique=True, nullable=False) email = ((120), unique=True, nullable=False) def __repr__(self): return '<User %r>' %
2. Initialize the migration warehouse
In the terminal, go to the root directory of the Flask application and run the following command to initialize the migration repository. This command will create a name calledmigrations
folder to store all migration files.
flask db init
Note: If you have not added Flask's command line interface (CLI) to your application, you may need to call it directly.flask_migrate
command line tool, or throughpython -m flask db init
run in the way.
3. Generate migration scripts
After modifying the model, a migration script needs to be generated that describes the changes from the current database schema to the updated database schema.
flask db migrate -m "Add User Model"
Here-m
The option allows you to specify a message for the migration that will appear at the head of the migration file to indicate the purpose or content of the migration.
4. Review the migration script
The generated migration script will be saved inmigrations
In the folder, the file name is usually similarversion_xxxx_migration_message.py
format. Before applying these changes to the database, it is recommended to review these scripts to make sure they correctly reflect your model changes.
3. Run database migration
1. Application migration
Once you are satisfied with the content of the migration script, you can apply the migration to the database through the following command.
flask db upgrade
This command looks for the latest migration script and applies it to the database. If the database schema is already up to date, this command will not perform any operations.
2. Downgrade migration
If you need to roll back to the previous database version, you can usedowngrade
Order.
flask db downgrade
By default,downgrade
The command will roll back to the previous migration version. If you need to roll back to a specific version, you can use--revision
Options specify the target version.
4. Other precautions
- Database backup: Before performing any migration, it is recommended to back up the database in case of unforeseen problems during the migration process.
- Migration script management: Over time, there may be many migration scripts in your application. It is recommended to review these scripts regularly to ensure they are still valid and to remove any scripts that are no longer needed.
- Migration dependencies: If your application depends on a specific database feature or version, make sure to consider these dependencies in the migration script.
- test: Before applying migrations to production databases, run them in a development or test environment to make sure they work as expected.
By following the above steps, you can effectively create and run database migrations in your Flask application, thereby managing changes in database schemas and ensuring consistency and integrity of your data. While this process may involve some complexity and challenges, it provides strong support and flexibility for database management during development.
The above is the detailed content of the implementation process of Flask creating and running database migration. For more information about Flask database migration, please pay attention to my other related articles!