Skip to content

Instantly share code, notes, and snippets.

@dvdotsenko
Created September 3, 2017 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvdotsenko/1265c2fb61e4d2091e0f81eedebe9854 to your computer and use it in GitHub Desktop.
Save dvdotsenko/1265c2fb61e4d2091e0f81eedebe9854 to your computer and use it in GitHub Desktop.
Python env vars apply to config
def apply_env_vars(module_name, env_var_prefix='productname', remove_module_prefix='config.'):
import os
import sys
env_var_prefix = '_'.join(
env_var_prefix.upper().split('.') +
module_name[len(remove_module_prefix):].upper().split('.')
) + '__'
module = sys.modules[module_name]
prefix_len = len(env_var_prefix)
for key in os.environ.keys():
if key.startswith(env_var_prefix):
value = os.environ[key]
key = key[prefix_len:]
original_value = getattr(module, key, None)
if original_value is not None:
value = type(original_value)(value)
setattr(module, key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment