Skip to content

Commit

Permalink
Remove dependency on HTTP CloudEvent implementation
Browse files Browse the repository at this point in the history
Signed-off-by: Federico Busetti <[email protected]>
  • Loading branch information
febus982 committed Aug 31, 2023
1 parent 7272113 commit ea2c85d
Showing 1 changed file with 8 additions and 11 deletions.
19 changes: 8 additions & 11 deletions cloudevents/pydantic/v2/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import base64
import datetime
import json
import typing

from cloudevents.exceptions import PydanticFeatureNotInstalled
Expand All @@ -28,7 +27,7 @@
"Install it using pip install cloudevents[pydantic]"
)

from cloudevents import abstract, conversion, http
from cloudevents import abstract, conversion
from cloudevents.exceptions import IncompatibleArgumentsError
from cloudevents.sdk.event import attribute

Expand Down Expand Up @@ -167,25 +166,23 @@ def check_base64_data_input(cls, data: typing.Any) -> typing.Any:
del data["data_base64"]
return data

@model_serializer(when_used="json")
def serialize_model(self) -> typing.Any:
@model_serializer(when_used="json", mode="wrap")
def serialize_model(self, handler: typing.Callable) -> typing.Dict[str, typing.Any]:
"""Performs Pydantic-specific serialization of the event.
Needed by the pydantic base-model to serialize the event correctly to json.
Without this function the data will be incorrectly serialized.
:param self: CloudEvent.
:param handler: The nested serialization handler.
:return: Event serialized as a standard CloudEvent dict with user specific
parameters.
"""
# Using HTTP from dict due to performance issues (from V1 implementation).
# We shouldn't use logic from other CloudEvent implementations.
# Mypy thinks `self` is missing in call to `model_dump`
event = http.from_dict(self.model_dump()) # type: ignore
event_json = conversion.to_json(event)
# Pydantic is known for initialization time lagging (from V1 implementation).
return json.loads(event_json)
model_dump: dict = handler(self)
if isinstance(self.data, (bytes, bytearray, memoryview)):
model_dump["data_base64"] = base64.b64encode(self.data).decode("ascii")
return model_dump

def _get_attributes(self) -> typing.Dict[str, typing.Any]:
return {
Expand Down

0 comments on commit ea2c85d

Please sign in to comment.