Common: Implement EventSerializer for pydantic objects

This commit is contained in:
Ilija Lazoroski 2022-09-09 17:09:54 +02:00
parent e0fb651c69
commit e756e0dbc3
2 changed files with 29 additions and 1 deletions

View File

@ -1,2 +1,2 @@
from .i_event_serialize import IEventSerializer from .i_event_serialize import IEventSerializer, JSONSerializable
from .event_serializer_registry import EventSerializerRegistry from .event_serializer_registry import EventSerializerRegistry

View File

@ -0,0 +1,28 @@
import logging
from typing import Type
from common.base_models import InfectionMonkeyBaseModel
from common.events import AbstractAgentEvent
from . import IEventSerializer, JSONSerializable
logger = logging.getLogger(__name__)
class PydanticEventSerializer(IEventSerializer):
def __init__(self, event_class: Type[AbstractAgentEvent]):
self._event_class = event_class
def serialize(self, event: AbstractAgentEvent) -> JSONSerializable:
if not issubclass(event.__class__, self._event_class):
raise TypeError(f"Event object must be of type: {InfectionMonkeyBaseModel.__name__}")
try:
return event.dict()
except AttributeError as err:
logger.error(f"Error occured while serializing an event {event}: {err}")
return None
def deserialize(self, serialized_event: JSONSerializable) -> AbstractAgentEvent:
return self._event_class.parse_obj(serialized_event)