Created
September 3, 2017 05:11
-
-
Save dvdotsenko/1265c2fb61e4d2091e0f81eedebe9854 to your computer and use it in GitHub Desktop.
Python env vars apply to config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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