yamlfile.py 853 B

1234567891011121314151617181920212223242526272829303132
  1. import codecs
  2. import yaml
  3. from .filebased import FileBasedSource
  4. __all__ = ("YamlFileSource",)
  5. class YamlFileSource(FileBasedSource):
  6. def __init__(self, *args, **kwargs):
  7. self.encoding = kwargs.pop("encoding", "utf-8")
  8. super(YamlFileSource, self).__init__(*args, **kwargs)
  9. def get_settings_from_file(self, file_path, settings, manager=None):
  10. content = codecs.open(file_path, "r", self.encoding).read().strip()
  11. if not content:
  12. return None
  13. content = yaml.safe_load(content)
  14. if not content:
  15. return None
  16. if not isinstance(content, dict):
  17. raise TypeError("YAML files must contain only mappings")
  18. for setting in settings:
  19. if setting.name in content:
  20. setting.value = content[setting.name]
  21. return settings