.ini file load environment variable

℡╲_俬逩灬. 提交于 2019-12-10 01:14:01

问题


I am using Alembic for migrations implementation in a Flask project. There is a alembic.ini file where the database configs must be specified:

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

Is there a way to specify the parameters from the environment variables? I've tried to load them in this way $(env_var) but with no success. Thanks!


回答1:


I've solved the problem by setting sqlalchemy.url in env.py as @dirn suggested.

config.set_main_option('sqlalchemy.url', <db_uri>) did the trick, where <db_uri> can be loaded from environment or config file.




回答2:


I was looking for a while how to manage this for mutli-databases

Here is what I did. I have two databases : logs and ohlc

According to the doc, I have setup the alembic like that

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

usage

SETTINGS=config.yml alembic upgrade head

Hope it can helps !



来源:https://stackoverflow.com/questions/37890284/ini-file-load-environment-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!