An ebook/comic library service and web client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
3.9 KiB

  1. """Handle Model Serialization."""
  2. import logging
  3. from typing import Dict, Callable, Any, List, Optional, Type
  4. from atheneum import errors
  5. from atheneum.db import db
  6. LOGGER = logging.getLogger(__name__)
  7. class BaseTransformer:
  8. """Base Model serializer."""
  9. type: Type[db.Model]
  10. def __init__(self, model: Type[db.Model]) -> None:
  11. """Initialize the base serializer."""
  12. self._fields: Dict[str, Callable[[db.Model], Any]] = {}
  13. self.model = model
  14. def serialize(self, options: Optional[List[str]]) -> Any:
  15. """Convert Model field and factories to dicts."""
  16. field_factories = self._serializers()
  17. if not options:
  18. options = list(field_factories.keys())
  19. ret = {}
  20. for key in options:
  21. if key not in field_factories:
  22. raise errors.ValidationError(
  23. 'Invalid key: %r. Valid keys: %r.' % (
  24. key, list(sorted(field_factories.keys()))))
  25. factory = field_factories[key]
  26. val = factory()
  27. if val is not None:
  28. ret[key] = val
  29. return ret
  30. def deserialize(self,
  31. json_model: dict,
  32. options: Optional[List[str]]) -> Any:
  33. """Convert dict to Model."""
  34. field_factories = self._deserializers()
  35. if not options:
  36. options = list(field_factories.keys())
  37. for key in options:
  38. if key not in field_factories:
  39. raise errors.ValidationError(
  40. 'Invalid key: %r. Valid keys: %r.' % (
  41. key, list(sorted(field_factories.keys()))))
  42. factory = field_factories[key]
  43. try:
  44. value = json_model[key]
  45. if value is not None:
  46. factory(self.model, value)
  47. except KeyError as key_error:
  48. LOGGER.error(
  49. 'Unable to transform field: %s %s', key, key_error)
  50. return self.model
  51. def _serializers(self) -> Dict[str, Callable[[], Any]]:
  52. """Field definitions."""
  53. raise NotImplementedError()
  54. def _deserializers(
  55. self) -> Dict[str, Callable[[db.Model, Any], None]]:
  56. """Field definitions."""
  57. raise NotImplementedError()
  58. _model_transformers: Dict[str, Type[BaseTransformer]] = {}
  59. def register_transformer(
  60. model_serializer: Type[BaseTransformer]) -> Type[BaseTransformer]:
  61. """Add a model to the serializer mapping."""
  62. model_name = model_serializer.type.__name__
  63. if model_name not in _model_transformers:
  64. _model_transformers[model_name] = model_serializer
  65. else:
  66. raise KeyError(
  67. ' '.join([
  68. 'A transformer for type "{}" already exists with class "{}".',
  69. 'Cannot register a new transformer with class "{}"'
  70. ]).format(
  71. model_name,
  72. _model_transformers[model_name].__name__,
  73. model_serializer.__name__))
  74. return model_serializer
  75. def serialize_model(model_obj: db.Model,
  76. options: Optional[List[str]] = None) -> Any:
  77. """Lookup a Model and hand off to the serializer."""
  78. try:
  79. return _model_transformers[
  80. type(model_obj).__name__](model_obj).serialize(options)
  81. except KeyError:
  82. raise NotImplementedError(
  83. '{} has no registered serializers'.format(model_obj.__name__))
  84. def deserialize_model(
  85. model_type: Type[db.Model],
  86. json_model_object: dict,
  87. options: Optional[List[str]] = None) -> db.Model:
  88. """Lookup a Model and hand it off to the deserializer."""
  89. try:
  90. transformer = _model_transformers[model_type.__name__]
  91. return transformer(
  92. transformer.type()).deserialize(json_model_object, options)
  93. except KeyError:
  94. raise NotImplementedError(
  95. '{} has no registered serializers'.format(model_type))