又一个python迁移工具
migrations的Python项目详细描述
用于python应用程序的简单的、与数据库无关的迁移工具。 灵感来自node migrations。
状态
这个项目现在处于测试阶段。可能会出现错误和中断更改。
功能
- 没有特定的数据库需求,可以将其用于任何调用数据库的操作。
- 很简单,只需生成迁移脚本并定义自解释 up()和down()函数。
- 在迁移脚本中使用导入来加载数据库绑定。与 与应用程序相同的数据库。
- 存储已执行迁移的序列。如果序列没有 匹配迁移目录中的脚本(例如合并后),中止并警告用户。
- tbd:可深度配置,包括资源获取和释放。
要求
目前只支持Python3。
安装
$ pip install migrations
注意,这个发行版提供了包和可执行文件 名为migrate的脚本,因此请检查它是否与 现有的包/脚本。通常,您都不应该安装 此工具是全局性的,也不能为一个项目安装多个迁移工具。
用法
usage: migrate [options] [action] actions: up [-h] [NAME|COUNT] (default) perform COUNT migrations or till given NAME (by default perform all available) down [-h] [NAME|COUNT] revert COUNT migrations or till given NAME (by default revert one) create [-h] NAME create new migration file show [-h] print all migrations in chronological order options: -h, --help show this help message and exit -v, --version show version and exit -d PATH, --migrations-dir PATH directory where migrations are stored -s PATH, --state-file PATH location of file which stores database state -t PATH, --template-file PATH location of template file for new migrations
每个迁移文件必须定义函数up()和down() 没有必要的参数。
简单的迁移示例:
importredisdb=redis.Redis(host='localhost',port=6379)defup():db.rpush('used_libraries','migrations')defdown():db.rpop('used_libraries','migrations')
当前工作目录的前缀是sys.path,因此 import迁移文件中的语句尝试查找请求的 首先是工作目录中的模块。你可以用这个来管理 单块应用程序和迁移的数据库访问 代码的。看一个例子。假设在工作目录中 我们有一个名为db的模块,它包含singleton对象 例如负责数据库连接 PyMySQL连接对象。
fromdbimportconnectiondefmanage_cursor(action):defwrap():withconnection.cursor()ascursor:action(cursor)connection.commit()returnwrap@manage_cursordefup(cursor):cursor.execute("INSERT INTO used_libraries (`name`) VALUES ('migrations')")@manage_cursordefdown(cursor):cursor.execute("DELETE FROM used_libraries WHERE `name`='migrations'")