Python_Flask_简单博客系统开发:数据库迁移——Mig

2018-01-26  本文已影响124人  ADark0915

使用Flask-Migrate完成数据库更新升级,Flask-Migrate插件是基于Alembic,Alembic是由大名鼎鼎的SQLAlchemy作者开发数据迁移工具。

操作步骤:

  1. 安装Flask-Migrate插件
(venv) $ pip install Flask-Migrate
  1. 修改Flask App部分的代码,以增加Migrate相关的Command
db = SQLAlchemy(app)
migrate = Migrate(app, db)
 
manager = Manager(app)
manager.add_command('db', MigrateCommand)
  1. 初始化
python manage.py db init
  1. 创建迁移仓库

首先还是需要安装flask-migrate插件

(venv) $ pip install flask-migrate

然后,我们来看下如何完成初始化

manage.py

from flask.ext.migrate import Migrate, MigrateCommand 
 
# ...
 
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

在数据库迁移可以维护之前,必须通过init子命令来创建一个迁移库:

(venv) $ python manage.py db init

这个命令创建一个migrations文件夹,里面存放了所有迁移脚本。

  Creating directory /home/adark0915/PycharmProjects/flasky/migrations ... done
  Creating directory /home/adark0915/PycharmProjects/flasky/migrations/versions
  ... done
  Generating /home/adark0915/PycharmProjects/flasky/migrations/README ... done
  Generating /home/adark0915/PycharmProjects/flasky/migrations/script.py.mako ... done
  Generating /home/adark0915/PycharmProjects/flasky/migrations/alembic.ini ... done
  Generating /home/adark0915/PycharmProjects/flasky/migrations/env.pyc ... done
  Generating /home/adark0915/PycharmProjects/flasky/migrations/env.py ... done
  Please edit configuration/connection/logging settings in
  '/home/adark0915/PycharmProjects/flasky/migrations/alembic.ini' before
  proceeding.

  1. 创建迁移脚本
(venv) $ python hello.py db migrate -m "initial migration"

在Alembic,数据库迁移工作由迁移脚本完成。这个脚本有两个函数,分别叫做upgrade()和downgrade()。upgrade()函数实施数据库更改,是迁移的一部分,downgrade()函数则删除它们。

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added column 'users.default'
INFO  [alembic.autogenerate.compare] Detected added column 'users.permissions'
INFO  [alembic.autogenerate.compare] Detected added index 'ix_users_default' on '['default']'
  Generating /home/adark0915/PycharmProjects/flasky/migrations/versions/d5ddba7501
  2e_initial_migration.py ... done
  1. 更新数据库
(venv) $ python hello.py db upgrade
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> d5ddba75012e, initial migration
/home/adark0915/PycharmProjects/flasky/venv/local/lib/python2.7/site-packages/alembic/util/messaging.py:69: UserWarning: Skipping unsupported ALTER for creation of implicit constraint
  warnings.warn(msg)

这样,就完成了数据库的更新升级。

上一篇下一篇

猜你喜欢

热点阅读