CloudEvents Python SDK
The CloudEvents Python SDK provides a simple and efficient way to create, parse, and send CloudEvents in Python applications. It supports all CloudEvents versions and various transport bindings. The current version is 2.0.0, with active development and regular releases.
Warnings
- breaking The CloudEvent attribute `contenttype` was renamed to `datacontenttype` in version 2.0.0 to align with the CloudEvents specification. Code using `event.contenttype` will break.
- breaking In version 2.0.0+, `CloudEvent.data` now consistently returns `bytes` or `None`. In earlier versions (1.x), it could return the original Python object type (e.g., `dict`, `str`).
- breaking Several utility functions and methods, such as `CloudEvent.FromInstance`, `CloudEvent.ToJsonString`, and direct `json.dumps` methods on CloudEvent objects, were removed in version 2.0.0.
- gotcha The `time` attribute of a CloudEvent must conform to RFC 3339 (e.g., `2018-04-05T17:31:00Z`). Incorrectly formatted timestamps might be accepted by the SDK but could cause issues with downstream consumers or spec validation.
Install
-
pip install cloudevents
Imports
- CloudEvent
from cloudevents.http import CloudEvent
- to_structured
from cloudevents.http import to_structured
- from_structured
from cloudevents.http import from_structured
Quickstart
from cloudevents.http import CloudEvent, to_structured
import json
import datetime
# Define CloudEvent attributes
attributes = {
"type": "com.example.someevent",
"source": "/mycontext/myapp",
"id": "A234-1234-1234",
"time": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z'),
"datacontenttype": "application/json"
}
# Define event data
data = {"message": "Hello, CloudEvents!", "value": 123}
# Create a CloudEvent instance
event = CloudEvent(attributes, data)
# Serialize the event to structured HTTP headers and body
headers, body = to_structured(event)
print("--- CloudEvent (Structured Mode) ---")
print("Headers:", headers)
print("Body:", body.decode('utf-8'))
print("\nEvent Data (original):")
print(event.data) # For v2.0.0, this returns bytes or None
print("Event Data (decoded):", json.loads(event.data.decode('utf-8')))