Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.json() unable to serialize datetime elements in data payload #213

Open
mrossi-kmx opened this issue May 16, 2023 · 3 comments
Open

.json() unable to serialize datetime elements in data payload #213

mrossi-kmx opened this issue May 16, 2023 · 3 comments

Comments

@mrossi-kmx
Copy link

Expected Behavior

The CloudEvent model, like Pydantic's BaseModel, can serialize of datetime properties to strings in the .json() function.

Actual Behavior

The CloudEvent model raises a ValueError from the standard library's json.dumps function when .json() is called on a model containing datetime properties in the data field.

Alternatively, if this is intentional behavior, it would be helpful to have some guidance around what the expected usage is when users want to have dates or timestamps in their CloudEvent data.

Steps to Reproduce the Problem

  1. Init a CloudEvent where some element of the data argument is a datetime instance.
  2. Call .json() on the CloudEvent instance

For example:

from datetime import datetime

from cloudevents.pydantic import CloudEvent

event = CloudEvent(attributes={'source': 'my.source', 'type': 'com.my.type'}, data={'dt': datetime.now()})

# raises TypeError
print(event.json())

By contrast, Pydantic's BaseModel is able to encode datetime properties:

from datetime import datetime

from pydantic import BaseModel

class MyModel(BaseModel):
  dt: datetime

foo = MyModel(dt=datetime.now())

# encodes dt as a string
print(foo.json())

Specifications

  • Platform: MacOS Ventura 13.2.1 (Intel)
  • Python Version: 3.9.9
@xSAVIKx
Copy link
Member

xSAVIKx commented May 16, 2023

Hey @mrossi-kmx,

Thx for opening the issue. And yes, currently JSON behavior is not configurable. The Pydantic model is able to perform the conversion while it uses a separate JSON serialization approach.

This should be improved all over the SDK as I mentioned here.

@mrossi-kmx
Copy link
Author

Thanks for your response @xSAVIKx! Do you/others have a recommendation for what to do with datetimes in the meantime? Just encode them as strings?

@xSAVIKx
Copy link
Member

xSAVIKx commented May 17, 2023

Thanks for your response @xSAVIKx! Do you/others have a recommendation for what to do with datetimes in the meantime? Just encode them as strings?

That's probably the best approach here. Or you can use Pydantic wrapper if that's ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants