.ini文件加载环境变量

dim*_*mmg 13 python ini flask alembic

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

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

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

dim*_*mmg 11

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

config.set_main_option('sqlalchemy.url', <db_uri>)做了诀窍,<db_uri>可以从环境或配置文件加载.

  • 您能为您的解决方案提供更多信息吗?我不确定这个 env.py 文件在哪里。 (4认同)

Con*_*che 11

我一直在寻找如何管理多数据库的方法

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

根据文档,我已经像这样设置了alembic

alembic init --template multidb
Run Code Online (Sandbox Code Playgroud)

alembic.ini

databases = logs, ohlc
[logs]
sqlalchemy.url = postgresql://botcrypto:botcrypto@localhost/logs
[ohlc]
sqlalchemy.url = postgresql://botcrypto:botcrypto@localhost/ohlc
Run Code Online (Sandbox Code Playgroud)

环境变量

[...]
# 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')
[...]
Run Code Online (Sandbox Code Playgroud)

配置.yml

databases:
    logs: postgresql://botcrypto:botcrypto@127.0.0.1:5432/logs
    ohlc: postgresql://botcrypto:botcrypto@127.0.0.1:5432/ohlc
Run Code Online (Sandbox Code Playgroud)

用法

SETTINGS=config.yml alembic upgrade head
Run Code Online (Sandbox Code Playgroud)

希望它能有所帮助!