Flask-Migrate是一个扩展,它以正确的方式配置Alembic以与Flask和Flask-SQLAlchemy应用程序一起使用
在之前的数据库操作中,我们新增一个字段是不是每次都得删除数据库表,然后再重新将新创建的数据库表映射到数据库中。这样操作是不是很蛋疼?是吧?于是sqlalchemy作者拜尔为了解决这一问题,开发了alembic这一迁移工具。
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 = Migrate(app, db)
manager = Manager(app)
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()
Assuming the above script is stored in a file named manage.py, all the database migration commands can be accessed by running the script:
$ python manage.py db init
$ python manage.py db migrate
$ python manage.py db upgrade
$ python manage.py db --help