cloudevents / cloudevents/sdk-python
`.json()` unable to serialize datetime elements in `data` payload
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 342
- Forks
- 65
- PR merge metrics
- No merged PRs in 30d
Description
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
- Init a CloudEvent where some element of the
dataargument is adatetimeinstance. - 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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue identifies cloudevents.pydantic.CloudEvent.json() as the entry point; start by comparing its datetime handling with Pydantic BaseModel.json(). Add a regression case using datetime in data and verify that serialization produces a string rather than raising. Confirm the behavior with the reproduction shown in the issue.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend-api-design
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100