_toml_serializer.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import toml # type: ignore
  12. from .._config import _Config
  13. from ..exceptions.exceptions import LoadingError
  14. from ._base_serializer import _BaseSerializer
  15. class _TomlSerializer(_BaseSerializer):
  16. """Convert configuration from TOML representation to Python Dict and reciprocally."""
  17. @classmethod
  18. def _write(cls, configuration: _Config, filename: str):
  19. with open(filename, "w") as fd:
  20. toml.dump(cls._str(configuration), fd)
  21. @classmethod
  22. def _read(cls, filename: str) -> _Config:
  23. try:
  24. config_as_dict = cls._pythonify(dict(toml.load(filename)))
  25. return cls._from_dict(config_as_dict)
  26. except toml.TomlDecodeError as e:
  27. error_msg = f"Can not load configuration {e}"
  28. raise LoadingError(error_msg) from None
  29. @classmethod
  30. def _serialize(cls, configuration: _Config) -> str:
  31. return toml.dumps(cls._str(configuration))
  32. @classmethod
  33. def _deserialize(cls, config_as_string: str) -> _Config:
  34. return cls._from_dict(cls._pythonify(dict(toml.loads(config_as_string))))