This article brings you an introduction to the usage of the flask-migrate extension (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
flask-migrate is a falsk extension used for data migration. It is usually used in conjunction with flask-sqlalchemy. I also introduced this extension in the previous article. Friends who need it can read it. Later, I will write about flask-sqlalchemy in more depth.
【config.py】
SQLALCHEMY_DATABASE_URI='mysql://root:mysql@127.0.0.1:3306/test' //数据库连接 SQLALCHEMY_TRACK_MODIFICATIONS=False
【data_migrate.py】
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager #这是一个做脚本调式的库,有时间我也会总结 from flask_migrate import Migrate,MigrateCommand app = Flask(__name__) app.config.from_envvar('config.py') db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) class User(db.Model): #创建一个模型类,用于做数据迁移 id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32)) if __name__ == '__main__': manager.run()
【Console test】
>>>python data_migrate.py db init //创建迁移存储库 >>>python data_migrate.py db migrate -m '版本名后缀' //生成初始迁移 >>>python data_migrate.py db upgrade //将迁移应用于数据库 //若有修改,可重复执行2/3这两条命令 >>>python 文件 db history //显示整个历史版本记录 【其他命令】 python data_migrate.py db --help //帮助,查找所有命令 python data_migrate.py db current //显示当前版本 python data_migrate.py db upgrade 版本号 //升级版本,不指定版本为最新版本 python data_migrate.py db downgrade 版本号 //降级数据库,不指定版本则是最老版本
The above is the detailed content of Introduction to the usage of flask-migrate extension (with code). For more information, please follow other related articles on the PHP Chinese website!