我已经研究了一段时间,但没有任何收获。如果我从命令行运行“alembic upgrade head”,效果很好。我想在 FastAPI 中执行此操作,这样当它启动时,它会升级数据库架构。所以经过大量搜索,我想出了这个方法:
async def run_migrations():
alembic_cfg = Config("alembic.ini")
url = str(engine.url)
async with engine.begin() as conn:
await conn.run_sync(alembic_cfg.set_main_option, "sqlalchemy.url", url)
await conn.run_sync(command.upgrade, alembic_cfg, "head")
我在 FastAPI 生命周期启动期间调用它。它给出了这个错误:
TypeError: Config.set_main_option() takes 3 positional arguments but 4 were given
我也尝试过:
await conn.run_sync(alembic_cfg.set_main_option("sqlalchemy.url", url))
但这让我:
TypeError: 'NoneType' object is not callable
run_sync 不喜欢我这样做吗?我没有向 set_main_option 传递 4 个参数。url 的值是正确的,因为我将其打印出来以确保无误。
或者有没有更简单/更好的方法从 fastapi 内部升级到 head?
谢谢
- SQLAlchemy 2.0.32
- uvicorn 0.30.6
- fastapi 0.112.1
- alembic 1.13.2