Database Migration
- During the development process, the database model needs to be modified, and the database will be updated after the modification. The most straightforward way to do this is to delete the old table, but the data is lost.
- A better solution is to use the database migration framework, which can track changes in the database schema and then apply the changes to the database.
- In flask, you can use the Flask-migrate extension to implement data migration. and integrated into the flask-script, all operations can be done by command.
- To export the database Migration command, Flask-migrate provides a Migratecommand class that can be attached to the Flask-script Manager object.
The first step is to install flask-migrate in a virtual environment.
pip install flask-migrate
The following is the code- level setting for database migration (no specific database is defined):
From flaskImport Flask # Importing FlaskFrom Flask_sqlalchemyImport SQLAlchemy # Importing SQLAlchemyFrom flask_migrateImport Migrate,migratecommand # importing Migratefrom flask_script import Manager # import terminal commands app = Flask (__name__) # Initialize Flaskmanager = Manager (APP) # Create terminal Command object app.config[ ' mysql://root:[email protected]:3306/flask_test ' # Link database app.config[ SQLALCHEMY_ Track_modifications '] = true # Turn on event Tracking db = SQLAlchemy (APP) # Initialize database object # use the migration class to save the application and database connection objects, the first parameter is an instance of flask, the second parameter is SQLAlchemy db instance migrate = Migrate (app,db) # Add a Database Migration command to the manager manager.add_ Command ( ' db ', Migratecommand)
< Span class= "Hljs-keyword" >< Span class= "hljs-string" > terminal command plane Operational Database Migration
#这个命令会创建migrations文件夹,所有迁移文件都放在里面,初始化时设置 python database.py db init
# 创建迁移脚本(给迁移文件起备注名) -m 后面为备注名
python database.py db migrate -m ‘initial migration‘
# 更新数据库
python database.py db upgrade
# 查看以前的版本
python app.py db history
# 回滚到指定版本
python app.py db downgrade 版本号
有不同简介欢迎交流
Use of database migrations in flask projects