介绍
flask-migrate时基于Alembic进行一个封装,并且集成到Flask中,而所有的迁移操作其实都是Alembic做的,他能跟踪模型的变化,并将变化映射到数据库中
一、安装
pip install flask-migrate
二、例子
创建数据库管理库:python manage.py db init
生成迁移脚本:python manage.py db migrate
映射到数据库中:python manage.py db upgrade
查看所有命令:python manage.py db --help
核心代码如下:
from flask_script import Manager # 命令行操作 from flask_migrate import Migrate,MigrateCommand from app import app from DB.exts import db # 必须导入数据库 import DB.models # 为app添加命令行操作功能 manager = Manager(app) # 绑定app和db Migrate(app,db) # 将MigrateCommand里面得命令加入子命令中 manager.add_command("db",MigrateCommand) # 创建数据库管理库:python manage.py db init # 生成迁移脚本:python manage.py db migrate # 映射到数据库中:python manage.py db upgrade # 查看所有命令:python manage.py db --help if __name__ == '__main__': manager.run()
从代码中看到导入了app和db,那么先看看app中得代码
from flask import Flask import settings from DB.exts import db app = Flask(__name__) app.config.from_object(settings) db = db.init_app(app) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/profile') def profile(): pass if __name__ == '__main__': app.run()
app中也导入了db和settings,先看看settings和exts代码吧
HOSTNAME = '127.0.0.1' PORT = 3306 DATABASE = 'db_demo' USERNAME = 'root' PASSWORD = '123456' # 链接数据库的字符串,固定格式 DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/{db}?charset=utf8".format( username = USERNAME, password = PASSWORD, host = HOSTNAME, port = PORT, db = DATABASE, ) SQLALCHEMY_DATABASE_URI = DB_URI SQLALCHEMY_TRACK_MODIFICATIONS = False DEBUG = True TEMPLATES_AUTO_RELOAD=True
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
最后我们看看models数据库模型
from DB.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)