【问题标题】:How to run a migration with Python Alembic by code?如何通过代码使用 Python Alembic 运行迁移?
【发布时间】:2016-12-25 13:16:49
【问题描述】:

我正在尝试使用 sqlAlchemy 和 Alembic 迁移 SQL 数据库。 我想直接在 Python 代码中制作简单的迁移脚本,而不是使用 Alembic CLI,如文档中所述。

我只在这个主题上发现了这个 SO 问题:Using Alembic API from inside application code

使用这个问题 + Flask-Alembic 源代码,我尝试了这些简单的命令。 引擎已链接到我的数据库,元数据包含迁移信息。

我想我已经很接近了,解决方案应该在一行代码中......我正在努力。

from alembic.config import Config
from alembic import command, autogenerate
from alembic.script import ScriptDirectory
from alembic.runtime.environment import EnvironmentContext

alembic_cfg = Config()
alembic_cfg.set_main_option("script_location", "migrations")
alembic_cfg.set_main_option("url", "postgresql://user:pass@postgres:5432/mydb")

alembic_script = ScriptDirectory.from_config(alembic_cfg)
alembic_env = EnvironmentContext(alembic_cfg, alembic_script)

conn = engine.connect()
alembic_env.configure(connection=conn, target_metadata=metadata)
alembic_context = alembic_env.get_context()

我可以使用以下命令来查看它是否有效并检测哪些字段必须迁移:

autogenerate.compare_metadata(alembic_context, metadata)
autogenerate.produce_migrations(alembic_context, metadata)

但是,我无法运行迁移。试了几个命令,总是报错……

例如,如果我运行:

with alembic_env.begin_transaction():
    alembic_env.run_migrations()

我明白了:

/usr/local/lib/python2.7/site-packages/alembic/runtime/migration.pyc in run_migrations(self, **kw)
    301         head_maintainer = HeadMaintainer(self, heads)
    302 
--> 303         for step in self._migrations_fn(heads, self):
    304             with self.begin_transaction(_per_migration=True):
    305                 if self.as_sql and not head_maintainer.heads:

TypeError: 'NoneType' object is not callable

谁能帮帮我。我认为解决方案是单行的,但我找不到如何在我的数据库上运行迁移...

关于信息,我从未使用 Alembic 在此数据库上进行过任何迁移,也许需要“init”?

非常感谢。

【问题讨论】:

    标签: python orm sqlalchemy alembic


    【解决方案1】:

    for step in self._migrations_fn(heads, self):

    在这里,我们将描述您要迁移的顺序。该序列由步骤组成,每个步骤都有step.migration_fn(**kw)

    如何解决

    您需要的最后一步是添加_migrations_fn,同时添加alembic_env.configure

    def do_upgrade(revision, context):
        return alembic_script._upgrade_revs(script.get_heads(), revision)
    
    alembic_env.configure(connection=conn, target_metadata=metadata, fn=do_upgrade)
    

    script.get_heads() 返回最后一次迁移。替换,如果你需要一个特定的修订,而不是最后一个。

    相关链接:

    【讨论】:

      猜你喜欢
      • 2019-12-19
      • 2017-07-12
      • 2012-10-27
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 2015-02-09
      • 2014-04-01
      • 2020-12-16
      相关资源
      最近更新 更多