簡體   English   中英

如何使用Python Alembic按代碼運行遷移?

[英]How to run a migration with Python Alembic by code?

我正在嘗試使用sqlAlchemy和Alembic遷移SQL數據庫。 我想直接在Python代碼中創建簡單的遷移腳本,而不是使用Alembic CLI,如文檔中所述。

我只在這個主題上找到了這個問題: 從應用程序內部代碼中使用Alembic API

使用這個問題+ 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”?

非常感謝。

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()返回上次遷移。 如果您需要特定的修訂,請替換,而不是最后一個。

相關鏈接:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM