from flask import Flask
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:westos@localhost/Todo'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
python manager.py db init 准备迁移环境
python manager.py db migrate 迁移
python manager.py db upgrade 提交
注:模型有变动时需要在命令行执行 python manager.py db migrate 和 python manager.py db upgrade重新映射到数据库
1). 创建迁移仓库(migrations目录)
python 练习1.py db init
1
2). 读取类的内容, 生成版本文件, 并没有真正在数据库中添加或删除;
python script.py db migrate -m "版本名后缀"
1
3). 在数据库中增删改, 也就是将迁移应用于数据库;
python script.py db upgrade
1
4). 检测是否成功?
mysql -uroot -pwestos
1
5). 去查看改变的历史状态;
python script.py db history
1
6). 返回指定的版本状态;降级数据库,不指定版本则是最老版本
python script.py db downgrade base
1
7). 显示当前版本
python data_migrate.py db current
1
8). 升级版本,不指定版本为最新版本
python data_migrate.py db upgrade 版本号
1
9). 帮助,查找所有命令
python data_migrate.py db --help
from flask_migrate import MigrateCommand, Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask import Flask
import pymysql
app = Flask(__name__)
pymysql.install_as_MySQLdb()
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:westos@localhost/Todo'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# app.config.from_pyfile('./config.py')
db = SQLAlchemy(app)
manager = Manager(app)
migrate = Migrate(app,db)
@manager.command
def dbinit():
"""数据库初始化信息"""
db.drop_all()
db.create_all()
print('数据库初始化成功')
manager.add_command('db', MigrateCommand)
if __name__ == "__main__":
# 将启动Manger实例接收命令行中的命令。
manager.run()