Created
August 15, 2017 06:24
-
-
Save DmitryBe/c463a008ba04960547ecfbf1d2bae6eb to your computer and use it in GitHub Desktop.
Load python config from json. Replace env vars templates with values
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 load_app_config(config_file_path): | |
''' | |
load json config file, example: | |
{ | |
"query": { | |
"port": 8000, | |
"env1": "${ENV1:-default_value}", | |
"env2": "${ENV2:-12}" | |
} | |
} | |
:param config_file_path: | |
:return: | |
''' | |
def _cast_to_type(s): | |
try: | |
return int(s) | |
except ValueError: | |
try: | |
return float(s) | |
except ValueError: | |
return s | |
def _substitude_env_vars(d): | |
for key in d.keys(): | |
v = d.get(key) | |
if isinstance(v, str): | |
m = re.match('\${(\w+)\:-(\w+)}', v) | |
if m: | |
env_name = m.group(1) | |
def_val = m.group(2) | |
env_val = os.environ.get(env_name) | |
if env_val is None: | |
env_val = _cast_to_type(def_val) | |
d[key] = env_val | |
elif isinstance(v, dict): | |
_substitude_env_vars(v) | |
if os.path.isfile(config_file_path): | |
with open(config_file_path, 'r') as f: | |
app_config = json.load(f) | |
_substitude_env_vars(app_config) | |
return app_config | |
else: | |
raise Exception('Configuration file not found: '.format(config_file_path)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment