Skip to content

Instantly share code, notes, and snippets.

@markgajdosik
Created April 23, 2015 11:16
Show Gist options
  • Save markgajdosik/bcb30a8c2a4509f8b93e to your computer and use it in GitHub Desktop.
Save markgajdosik/bcb30a8c2a4509f8b93e to your computer and use it in GitHub Desktop.
def save_configuration():
'''
Saves program configuration in the `config` module to a JSON file specified
via `config.general.CONFIG_PATH`. The function will skip any configuration
directives not listed in the provided `_ADJUSTABLE` lists.
'''
log.info('Saving program configuration.')
configuration = {}
# Get all section classes in the `config` module.
sections = inspect.getmembers(config, inspect.isclass)
# For each obtained section, get a list of its directives and their values.
for section_name, section in sections:
log.info('> Processing section "%s".', section_name)
adjustable = section._ADJUSTABLE
directives = inspect.getmembers(section,
lambda member: not(inspect.isroutine(member)))
# Store the list of directives to a dictionary within the
# `configuration`, skipping any special attributes.
configuration[section_name] = {}
for name, value in directives:
if name not in adjustable or name.startswith('_'):
continue
configuration[section_name][name] = value
log.info('> > %s = %s', name, value)
# Store the configuration as a JSON into a file.
with open(config.general.CONFIG_PATH, 'w') as f:
UTF8Writer = codecs.getwriter('utf-8')
f = UTF8Writer(f)
json.dump(configuration, f, ensure_ascii=False, sort_keys=True,
indent=4, separators=(',', ': '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment