简体   繁体   中英

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

For example, now I have this .ini file:

[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:

[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. 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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