Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing OS environment variables from Jinja2 template

Tags:

Is it possible to access a OS environment variable directly from a Jinja2 template?

like image 876
Roberto Aloi Avatar asked Sep 16 '14 06:09

Roberto Aloi


People also ask

What is Autoescape in Jinja2?

When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.

How do I set an environ variable in OS?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.


1 Answers

Following @Renier's pointer about custom filters in the comments, I figured out a possible solution.

Define a custom filter:

def env_override(value, key):   return os.getenv(key, value) 

Install the filter in the environment:

env.filters['env_override'] = env_override 

Use the filter as follows:

"test" : {{ "default" | env_override('CUSTOM') }} 

Where the appropriate environment variable can be set as:

export CUSTOM=some_value 

If the environment variable is set the output will be:

"test" : some_value 

Otherwise:

"test" : default 
like image 127
Roberto Aloi Avatar answered Sep 18 '22 19:09

Roberto Aloi