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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值