是否可以将 alembic 连接字符串存储在 alembic.ini 之外?

新手上路,请多包涵

我将 Alembic 与 SQLAlchemy 一起使用。对于 SQLAlchemy,我倾向于遵循一种模式,即不将连接字符串与版本化代码一起存储。相反,我有文件 secret.py 包含任何机密信息。我把这个文件名放在我的 .gitignore 中,所以它不会在 GitHub 上结束。

这种模式工作正常,但现在我开始使用 Alembic 进行迁移。看来我无法隐藏连接字符串。相反,在 alembic.ini 中,您将连接字符串作为 配置参数

 # the 'revision' command, regardless of autogenerate
# revision_environment = false

sqlalchemy.url = driver://user:pass@localhost/dbname

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembi

我担心我会不小心提交一个包含数据库用户名/密码信息的文件。我宁愿将此连接字符串存储在一个地方,避免意外将其提交给版本控制的风险。

我有什么选择?

原文由 Doug T. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 514
1 个回答

昨天我遇到了同样的问题,并找到了以下解决方案。我在 alembic/env.py 中执行以下操作:

 # this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# this will overwrite the ini-file sqlalchemy.url path
# with the path given in the config of the main code
import config as ems_config
config.set_main_option('sqlalchemy.url', ems_config.config.get('sql', 'database'))

ems_config 是一个保存我的配置数据的外部模块。

config.set_main_option(...) 实质上覆盖了 sqlalchemy.url alembic.ini 文件的 [alembic] 5321fd51cdefed39b-0 部分中的键在我的配置中,我只是将其保留为黑色。

原文由 Tammo Heeren 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题