CloudEvents Python SDK

2.0.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This example demonstrates how to create a CloudEvent with specified attributes and JSON data, then serialize it into HTTP structured mode headers and body. It also shows how to access the event's data (which is bytes in v2.0.0+).

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')))

view raw JSON →