flask_migrate:用来做数据库迁移的扩展,配合flask_script

flask_migrate:用来做数据库迁移的扩展,配合flask_script

作用: 避免模型类发生改变之后,导致数据库数据丢失,可以迁移解决.

操作流程:


1. 安装包,导入
    flask_migrate提供了两个类: Migrate, MigrateCommand
    flask_script: 提供的是: Manager
2. 使用Manager管理app, 使用Migrate将app和db进行关联
3. 使用MigrateCommand添加一个操作命令
4. 使用命令进行迁移操作
    1.生成迁移文件
    python xxx.py db init

    2.生成迁移脚本
    python xxx.py db migrate -m '注释'

    3.更新迁移脚本到数据库
    python xxx.py db upgrade [version]
    python xxx.py db downgrade [version] #有风险

    4.其他
    python xxx.py db history
    python xxx.py db show
from flask import Flask
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from flask_sqlalchemy import  SQLAlchemy

app = Flask(__name__)

#数据库配置信息
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@localhost:3306/data2"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

#创建ORM对象
db = SQLAlchemy(app)

# 使用Manager管理app,
manager = Manager(app)
# 使用Migrate将app和db进行关联
Migrate(app,db)
# 使用MigrateCommand添加一个操作命令
manager.add_command("db",MigrateCommand)

#定义模型类
class Student(db.Model):
    __tablename__ = "students"
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64))
    age = db.Column(db.Integer)
    money = db.Column(db.Integer)

@app.route('/')
def hello_world():

    return "helloworld"

if __name__ == '__main__':
    manager.run()

猜你喜欢

转载自blog.csdn.net/weixin_40420525/article/details/80896648
今日推荐