Python SSE Client

0.0.27 · maintenance · verified Thu Apr 16

The `sseclient` library (version 0.0.27) is a Python client for consuming Server-Sent Events (SSE) streams, also known as EventSource. It provides an `SSEClient` class that acts as an iterator, allowing easy processing of messages from a server. This version, last updated in September 2020, handles automatic reconnections and parses event data. While functional, it is no longer actively developed, with more recent and actively maintained forks (e.g., `sseclient-py`) addressing modern Python features and known issues.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an SSE endpoint using `requests` and iterate over incoming Server-Sent Events with `SSEClient`. Each `event` object typically has `data`, and optional `id`, `event` (type), and `retry` attributes.

import requests
from sseclient import SSEClient
import os

# Replace with your actual SSE endpoint URL
sse_url = os.environ.get('SSE_ENDPOINT_URL', 'http://localhost:8000/events')

try:
    # Establish a streaming connection using requests
    response = requests.get(sse_url, stream=True, headers={'Accept': 'text/event-stream'})
    response.raise_for_status() # Raise an exception for HTTP errors

    client = SSEClient(response)

    print(f"Connected to SSE stream at {sse_url}. Listening for events...")
    for event in client.events():
        if event.data:
            print(f"Received Event (ID: {event.id}, Type: {event.event}): {event.data}")
        else:
            print(f"Received heartbeat/empty event (ID: {event.id}, Type: {event.event})")

except requests.exceptions.RequestException as e:
    print(f"Error connecting to SSE stream: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →