configurator.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import json
  2. import pathlib
  3. class configurator_exception(Exception):
  4. pass
  5. class configurator:
  6. def __init__(self, config_path: pathlib.Path | None) -> None:
  7. if config_path is None:
  8. config_path = self.default_path
  9. if not config_path.is_file() or not config_path.exists():
  10. raise configurator_exception(
  11. "Config file \"" \
  12. + str(config_path) \
  13. + "\" not exists."
  14. )
  15. with config_path.open() as handler:
  16. try:
  17. self.__storage = json.loads(handler.read())
  18. except Exception as error:
  19. raise configurator_exception(
  20. "Config file is not correct. Error: \""
  21. + str(error)
  22. + "\"."
  23. )
  24. @staticmethod
  25. def default_path() -> pathlib.Path:
  26. return pathlib.Path("./config.json")
  27. def get(self, key: str) -> any:
  28. result = self.__storage
  29. for count in key.split("."):
  30. count = count.strip()
  31. if len(count) == 0:
  32. raise configurator_exception("Empty slot in key.")
  33. if not count in result:
  34. raise configurator_exception(
  35. "\"" \
  36. + count \
  37. + "\" not exists in configuration storage."
  38. )
  39. result = result[count]
  40. @
  41. return result