问题描述
我正在使用管理数据库迁移,并希望使用由 alembic init
生成的默认文件,无需对 env.py
进行任何修改(例如,)或 alembic。 ini
(例如,)来管理我的数据库从脚本的迁移。
I'm managing database migrations with Alembic and would like to use the default files generated by alembic init
without any modifications to env.py
(e.g., setting target_metadata
) or alembic.ini
(e.g., setting sqlalchemy.url
) to manage migrations of my database from scripts.
例如,喜欢使用基于的脚本,如下所示:
For example, I'd like to use a command based script like the following:
import os
from alembic.config import Config
from alembic import command
from myapp import db
alembic_cfg = Config(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'alembic.ini'))
alembic_cfg.set_main_option("sqlalchemy.url",
os.environ['DATABASE_URL'])
alembic_cfg.set_main_option("script_location",
os.path.join(os.path.abspath(os.path.dirname(__file__)), '.db_migrations'))
alembic_cfg.set_main_option("target_metadata", db.metadata) # This doesn't work!
command.revision(alembic_cfg, message='Test of new system', autogenerate=True)
command.upgrade(alembic_cfg, 'head')
这一切都可以按需运行,除了,指示的行失败了,我看不到设置方法 target_metadata
(而不是编辑 env.py
)。
This all works as desired, except that the indicated line fails, and I don't see a way to set the target_metadata
(other than editing env.py
).
如何在上面的脚本(类似)中使用Alembic的命令API,以编程方式设置Alembic所需的 target_metadata
?
How can I programmatically set the target_metadata
required by Alembic in (something like) the script above, which uses Alembic's command API?
推荐答案
长的答案是您没有在那里设置元数据,而是在创建 MigrationContext
时进行了设置。这要求您创建一个 Config
,然后创建一个 ScriptDirectory
,然后创建一个 EnvironmentContext $首先。然后,您需要在运行修订以自己设置环境时正确使用这些对象。
The long answer is that you don't set metadata there, you set it when creating the MigrationContext
. Which requires that you create a Config
, then a ScriptDirectory
, then an EnvironmentContext
first. Then you need to use these objects correctly when running revisions to set up the environment yourself.
简短的回答是,有两个扩展(我知道)可以集成Flask-SQLAlchemy和Alembic为您服务。 已经存在了一段时间,并且提供了一个直接的包装
The short answer is that there are two extensions (that I know of) that integrate Flask-SQLAlchemy with Alembic for you. Flask-Migrate has been around for a while and provides pretty much a straight wrapper around the basic commands from Alembic.
(由我编写)(与同名的旧项目无关,该旧项目尚未开发)与Flask和Alembic紧密集成。它公开了Alembic的内部结构,并与Flask开发人员版本一起使用,但更新且更具实验性。
Flask-Alembic (written by me) (not related to an older project of the same name that is not in development) provides tighter integration with Flask and Alembic. It exposes Alembic's internals and works with the Flask dev version, but is newer and more experimental.
它们都得到了积极维护。如果您需要了解内部知识,请选择Flask-Alembic。如果只需要命令,请选择Flask-Migrate。
They are both actively maintained. If you need to get at the internals, chose Flask-Alembic. If you just need the commands, choose Flask-Migrate.
这篇关于如何以编程方式设置Alembic要求与命令API一起使用的“ target_metadata”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!