1. 安装migrate模块
pip install flask_migrate
2. 创建manage对象,并接管app和db对象
manager = Manager(app, db)
3. 将数据库迁移操作集成到script中
manager.add_command(‘db‘, MigrateCommand)
案例代码:
from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyfrom flask_script import Managerfrom flask_migrate import Migrate, MigrateCommandapp = Flask(__name__)app.config[‘SQLALCHEMY_DATABASE_URI‘]=‘mysql://root:mysql@127.0.0.1:3306/flask_01‘manager = Manager(app)db = SQLAlchemy(app)migrate = Migrate(app, db)# 使用migrate集成到scriptmanager.add_command(‘db‘, MigrateCommand)class Book(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), nullable=True) hero_set = db.relationship(‘Hero‘, backref=‘book‘, lazy=‘dynamic‘)class Hero(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), nullable=True) book_id = db.Column(db.Integer, db.ForeignKey(‘book.id‘))@app.route(‘/‘)def index(): return ‘index‘if __name__ == ‘__main__‘: manager.run()
使用shell脚本执行数据库迁移
1. 创建makemigrations文件夹,及其相关文件。
python 文件名 init
2. 创建数据库迁移文件
python 文件名 migrate
3. 执行迁移文件
python 文件名 upgrade