Failures:
python -m example
SERVICE_USER=foo python -m example
Valid:
SERVICE_USER=foo SERVICE_PASS=bar python -m example
Run directly from zip:
PYTHONPATH=example.zip SERVICE_USER=foo SERVICE_PASS=bar python -m example
"""Example Module | |
Quick Example of a traverse funtion to verify all required values have been set by the user. | |
""" |
"""Entrypoint | |
Attempt to use the configuration, and printout the super secret string | |
""" | |
from example.config import get_config | |
def main(): | |
print("https://{user}:{pass}@{host}".format(**get_config().service)) | |
if __name__ == '__main__': | |
main() |
import os | |
import yamlsettings | |
def validate(settings): | |
"""Asserts if a value in the required_keys paths is not defined | |
""" | |
check_paths = [x.split('.') for x in settings.required_keys] | |
def _null_travers(path, node): | |
if node is None and any(path[:len(x)] == x for x in check_paths): | |
raise RuntimeError("{} is not set".format(".".join(path))) | |
return None | |
settings.traverse(_null_travers) | |
def init(): | |
"""The initialization of Configuration. | |
""" | |
if _CONFIG['init']: | |
return | |
yaml_data = pkgutil.get_data("example", "settings.yaml") | |
app_settings = yamlsettings.yamldict.load(yaml_data) | |
yamlsettings.update_from_env(app_settings) | |
validate(app_settings) | |
_CONFIG['settings'] = app_settings | |
_CONFIG['init'] = True | |
def get_config(): | |
"""Get the current configuration. | |
""" | |
if not _CONFIG['init']: | |
init() | |
return _CONFIG['settings'] | |
_CONFIG = { | |
'init': False, | |
'settings': None, | |
} |
--- | |
service: | |
host: google.com | |
user: null | |
pass: null | |
foo_pass: bad example password | |
required_keys: | |
- service | |
- foo_pass |