5.Flask-Migrate
1.1.项目结构重构
(1)config.py
DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/flask_migrate?charset=utf8" SQLALCHEMY_DATABASE_URI = DB_URI
(2)创建exts.py(防止循环引用报错)
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
(3)创建models.py
from exts import db class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(50),nullable=False)
(4)flask_migrate_demo.py
from flask import Flask from exts import db import config app = Flask(__name__) app.config.from_object(config) db.init_app(db) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
1.2.flask-migrate的使用
flask-migrate是基于alembic进行的一个封装,并集成到flask中,而所有的迁移操作其实都是alembic做的,它能跟踪模块的变化,并将变化映射到数据库中。
(1)安装
pip install flask-migrate
(2)manage.py
from flask_script import Manager from flask_migrate_demo import app from exts import db import models #这个一定要导入 from flask_migrate import Migrate,MigrateCommand manager = Manager(app) Migrate(app,db) manager.add_command("db",MigrateCommand) #把所有命令放到db里面 if __name__ == '__main__': manager.run()
(3)初始化
python manage.py db init
(4)创建迁移脚本
python manage.py db migrate -m '第一次提交'
(5)生成到数据库
python manage.py db upgrade
目录结构
posted on 2018-05-28 16:01 zhang_derek 阅读(947) 评论(0) 编辑 收藏 举报