数据迁移(2017.12.27)

1. pip install flask-migrate  #Flask-Migrate 是一个数据迁移框架,需要通过Flask-script库来操作.

2. pip install flask-script  #通过命令行来操作Flask

 

3. 新建模型更改文件:manage.py

 

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from myqa import app
from exts import db

from models import Question, Comment

manager = Manager(app) #Manager只有一个参数:一个Flask实例
migrate = Migrate(app, db) #使用Migrate绑定app和db
manager.add_command('db', MigrateCommand) ##添加迁移脚本命令,命令行输入python manage.py db migrate

if __name__ == '__main__':
manager.run() #启动Manger实例接收命令行中的命令。
from flask_script import Manager
from flask_migrate import Migrate,MigrateCommand
from untitled2 import app
from exts import db
from models import User,Comment,Question

manage=Manager(app)
migrate=Migrate(app,db)
manage.add_command('db',MigrateCommand)

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

4. 要models.py发生改变后,在cmd命令行,进到manage.py所在的路径,执行:

(1)初始化迁移环境,只运行一次
python manage.py db init

(2)生成迁移文件,模型改变了就需要执行
python manage.py db migrate

(3)映射到数据库表中
python manage.py db upgrade

 

 

posted @ 2017-12-27 16:02  赖黛俐  阅读(232)  评论(0编辑  收藏  举报