Skip to content

Instantly share code, notes, and snippets.

@ramboldio
Created November 28, 2016 11:24
Show Gist options
  • Save ramboldio/bca7771dad2de80b4de7479cae01a0ce to your computer and use it in GitHub Desktop.
Save ramboldio/bca7771dad2de80b4de7479cae01a0ce to your computer and use it in GitHub Desktop.
Load .json server configuration sublime text style
# imports the settings from the config files
import json
"""
EXAMPLE:
.json
postgres {
database : ..
}
.py
from config import Config
config = Config()
config.postgres["database"]
"""
class Config:
def __init__(self):
data = json.load(open("config_default.json"))
data_user = json.load(open("config_user.json"))
data = check_user_config(data, data_user)
self.__dict__ = data
# TODO add debug to config and assign it to __debug__ variable
if __debug__:
print("Active configuration:")
print(data)
def check_user_config(config_dict, user_dict):
"""recursively check if config_user has other values than config_default and override the latter
Args:
- config_dict (dict): original default configs as dict
- user_dict (dict): user configs which contain the only the settings which should be overridden
Returns:
- dict: the usable config data
"""
for key, value in config_dict.items():
# recursive call if value is a dict itself
if isinstance(value, dict):
if key in user_dict.keys():
check_user_config(value, user_dict[key])
else:
# no neeed to further go down the tree if keys dont match
pass
else:
if key in user_dict:
# if keys match go with the value of data_user
config_dict[key] = user_dict[key]
return config_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment