Skip to content

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

Open
@mrossi-kmx

Description

@mrossi-kmx

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions