Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 874
Stefano Avatar asked May 25 '18 15:05

Stefano


1 Answers

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)
like image 114
Michael Merickel Avatar answered Oct 18 '22 09:10

Michael Merickel