简体   繁体   English

我如何在Pyramid上的.ini文件中使用环境变量?

[英]How i can use environment variables on .ini file in Pyramid?

For example, now I have this .ini file: 例如,现在我有这个.ini文件:

[DEFAULT]
db_user = user_test
db_password = psw_test
db_host = localhost
db_name = db_test

...

I want to do: 我想要做:

export ENV_DB_USER=user_test
export ENV_DB_PSW=psw_test
export ENV_DB_HOST=localhost
export ENV_DB_NAME=db_test

Then I want to do somethings like this in .ini file: 然后我想在.ini文件中做这样的事情:

[DEFAULT]
db_user = ${ENV_DB_USER}
db_password = ${ENV_DB_PSW}
db_host = ${ENV_DB_HOST}
db_name = ${ENV_DB_NAME}

...

I have try to use %()s syntax but unfortunately not working. 我尝试使用%()的语法,但遗憾的是无法正常工作。 Where I'm doing wrong? 我做错了什么?

Thanks :) 谢谢 :)

Unfortunately they are not supported right now - you have to load them at runtime instead of in the ini file itself. 不幸的是,它们现在不受支持 - 您必须在运行时而不是在ini文件本身中加载它们。 A common approach in my apps is to define a render-config script which takes a site.ini.in template and renders it out to site.ini using jinja2 with env vars available to it. 我的应用程序中的一个常见方法是定义一个render-config脚本,该脚本采用site.ini.in模板并使用jinja2将其呈现给site.ini使用env vars。 It's not very satisfying but it does work well. 它不是很令人满意,但它确实运作良好。

import jinja2
import os

def multiline(val):
    lines = (l.strip() for l in val.strip().split('\n'))
    return '\n    ' + '\n    '.join(lines)

def main(cli, args):
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.getcwd()),
        undefined=jinja2.StrictUndefined,
    )
    env.filters['multiline'] = multiline

    template = env.get_template(args.template)
    result = template.render({
        'env': os.environ,
    })

    with open(args.config_file, 'w', encoding='utf8') as fp:
        fp.write(result)

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

相关问题 如何访问 Pyramid .ini 文件中的自定义部分? - How can I access a custom section in a Pyramid .ini file? 我可以将环境变量添加到 python 记录器 ini 文件配置吗? - Can I add environment variables to a python logger ini file configuration? 如何使用pyramid.wsgi中的ini文件的相对路径作为pyramid.paster.get_app的参数? - How to use a relative path for the ini file in pyramid.wsgi as argument of pyramid.paster.get_app? 如何在 config.ini 文件中加载环境变量? - How to load environment variables in a config.ini file? 在Pyramid Web框架中,如何从外部文件中将敏感设置导入development.ini / production.ini? - In the Pyramid web framework, how do I source sensitive settings into development.ini / production.ini from an external file? 我可以在金字塔中拥有多个ini配置文件吗? - Can I have multiple ini config files in Pyramid? 如何在金字塔中使用常见的ini配置(开发和生产之间)? - How to use a common ini configuration (between development and production) in pyramid? 将变量传递给Pyramid上的development.ini - Pass variables to development.ini on Pyramid 我可以在Alembic上使用.py文件而不是.ini文件吗? - Can I use .py file instead of .ini file on alembic? 在 Pyramid 中,如何根据上下文内容使用不同的渲染器? - In Pyramid, how can I use a different renderer based on contents of context?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM