# python flask-migrate 迁移数据库
Alembic(Database migration 数据迁移跟踪记录)提供的数据库升级和降级的功能。它所能实现的效果有如 Git 管理项目代码一般。
这里要用到俩个插件, 都安装下
pip install Flask-Migrate
pip install Flask-Script
官方文档给出的例子:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
# 初始化 migrate
# 两个参数一个是 Flask 的 app,一个是数据库 db
migrate = Migrate(app, db)
# 初始化管理器
manager = Manager(app)
# 添加 db 命令,并与 MigrateCommand 绑定
manager.add_command('db', MigrateCommand)
# 构建我们的数据模型
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128))
if __name__ == '__main__':
manager.run()
初始化 DB
python manage.py db init
这里如果你的数据模型或者数据库连接是外部引用的要注意路径问题
# 在上面加上这些指向根目录
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
查看指令 manager db 的可用选项
>>> python manage.py db
usage: Perform database migrations
Perform database migrations
positional arguments:
{init,revision,migrate,edit,merge,upgrade,downgrade,show,history,heads,branches,current,stamp}
init Creates a new migration repository
revision Create a new revision file.
migrate Alias for 'revision --autogenerate'
edit Edit current revision.
merge Merge two revisions together. Creates a new migration
file
upgrade Upgrade to a later version
downgrade Revert to a previous version
show Show the revision denoted by the given symbol.
history List changeset scripts in chronological order.
heads Show current available heads in the script directory
branches Show current branch points
current Display the current revision for each database.
stamp 'stamp' the revision table with the given revision;
don't run any migrations
optional arguments:
-?, --help show this help message and exit
基本上常用的命令就是:
# 追踪生成版本 -m 后面的是自定义的别名
>>> python manage.py db migrate -m "xxx"
# 根据文件生成数据库 最新生成的记录
>>> python manage.py db upgrade
# 获取 History ID
>>> python manage.py db history
# 回滚到某个 history
>>> python manage.py db downgrade <history_id>
具体的内容可以看我的GitHub上的源码:https://github.com/huzidabanzhang/python-admin/blob/master/trunk/tools/manage.py