使用ORM时,需要执行迁移操作以便在模型和持久化数据之间保持同步。我们使用Flask-Migrate这个扩展来完成该任务。
首先安装:
$ pip install flask-migrate $ pip install flask_script
然后在代码中引入:
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand
进行必要的配置:
migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand)
运行管理器:
if __name__ == '__main__': manager.run()
相关推荐:《Python视频教程》
完整的代码如下:
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'] = 'postgresql://localhost/appdb'db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand)class Post(db.Model): id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(80), unique=True) post_text = db.Column(db.String(255)) def __init__(self, title, post_text): self.title = title self.post_text = post_text@app.route('/')def index(): return "Hello World"if __name__ == "__main__": manager.run()
使用如下的命令初始化Alembic:
$ python app.py db init Creating directory /Users/Vihar/Desktop/flask-databases/migrations ... done ... ... ... Generating /Users/Vihar/Desktop/flask-databases/migrations/alembic.ini ... done
执行第一个迁移任务:
$ python app.py db migrate INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.autogenerate.compare] Detected added table 'post'Generating /Users/Vihar/Desktop/flask-databases/migrations/versions/ed3b3a028447_.py ... done
一旦上述命令执行完毕,我们的数据表就会创建成功。现在更新数据库:
$ python app.py db upgrade
相关推荐: