繁体   English   中英

.ini文件加载环境变量

[英].ini file load environment variable

我在Flask项目中使用Alembic进行迁移实施。 有一个alembic.ini文件,其中必须指定数据库配置:

sqlalchemy.url = driver://user:password@host/dbname

有没有办法从环境变量中指定参数? 我试图以这种方式加载它们$(env_var)但没有成功。 谢谢!

我已经通过设置解决了这个问题sqlalchemy.urlenv.py作为@dirn建议。

config.set_main_option('sqlalchemy.url', <db_uri>)完成了这个技巧,其中<db_uri>可以从环境或配置文件加载。

我正在寻找一段时间如何为mutli-databases管理这个问题

这就是我做的。 我有两个数据库: logsohlc

根据文件 ,我已经设置了类似的蒸馏器

alembic init --template multidb

alembic.ini

databases = logs, ohlc
[logs]
sqlalchemy.url = postgresql://botcrypto:botcrypto@localhost/logs
[ohlc]
sqlalchemy.url = postgresql://botcrypto:botcrypto@localhost/ohlc

env.py

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

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')

# overwrite alembic.ini db urls from the config file
settings_path = os.environ.get('SETTINGS')
if settings_path:
    with open(settings_path) as fd:
        settings = conf.load(fd, context=os.environ) # loads the config.yml
    config.set_section_option("ohlc", "sqlalchemy.url", settings["databases"]["ohlc"])
    config.set_section_option("logs", "sqlalchemy.url", settings["databases"]["logs"])
else:
    logger.warning('Environment variable SETTINGS missing - use default alembic.ini configuration')
[...]

config.yml

databases:
    logs: postgresql://botcrypto:botcrypto@127.0.0.1:5432/logs
    ohlc: postgresql://botcrypto:botcrypto@127.0.0.1:5432/ohlc

用法

SETTINGS=config.yml alembic upgrade head

希望它可以帮助!

只是为了添加到现有的答案, alembic 教程有这样的说法:

  • sqlalchemy.url - A URL 通过 ZD233B99A3CCB7F38A27Z26DZ 连接到数据库。 此配置值仅在 env.py 文件调用它们时使用; 在“通用”模板中,run_migrations_offline() function 中对config.get_main_option("sqlalchemy.url")的调用和run_migrations_offline() ZC1C425268E68389D1AB4A 中对engine_from_config(prefix="sqlalchemy.") run_migrations_online()调用是 thiskeyC1C425268E683895D1AB4A参考。 如果 SQLAlchemy URL 应该来自其他来源,例如来自环境变量或全局注册表,或者如果迁移环境使用多个数据库 URL,则鼓励开发人员更改 env.py 文件以使用任何合适的方法为了获取数据库 URL 或 URL。

建立在@dimmg 的回答之上:
可以在env.py文件中覆盖sqlalchemy.url中指定的alembic.ini

单一数据库

env.py

插入

config.set_main_option('sqlalchemy.url', <db_uri>)

其中 <db_uri> 可以从环境或配置文件中加载。

多数据库

env.py

假设您有一个包含数据库db_adb_b的多数据库设置,插入

config.set_section_option('db_a', 'sqlalchemy.url', <db_uri_a>)
config.set_section_option('db_b', 'sqlalchemy.url', <db_uri_b>)

其中 <db_uri_a> 和 <db_uri_b> 分别是db_adb_b的数据库 URI,可以从环境或配置文件中加载。

笔记

还要确保在alembic.ini文件中指出指定的参数在env.py文件中被覆盖。 对于sqlalchemy.url env.py部分。
这有望在您或合作者稍后返回项目时避免一些困惑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM