SSE Client for Python

1.9.0 · active · verified Thu Apr 09

sseclient-py is a Python library providing a client for Server-Sent Events (SSE). It simplifies consuming event streams by parsing the SSE protocol over HTTP. The current stable version is 1.9.0, with releases typically focused on bug fixes and feature additions rather than frequent breaking changes.

Warnings

Install

Imports

Quickstart

Connects to an SSE stream using the `sseclient-py` library with `requests`. It demonstrates how to initialize the client and iterate over incoming events, highlighting the crucial `stream=True` parameter for `requests` to ensure proper streaming behavior.

import sseclient
import requests
import os

# Replace with your SSE stream URL (or set SSE_STREAM_URL environment variable)
stream_url = os.environ.get('SSE_STREAM_URL', 'http://localhost:8000/stream')

try:
    # IMPORTANT: stream=True is crucial for long-lived connections.
    # The sseclient-py library expects an iterable response body,
    # which requests.get(..., stream=True) provides.
    response = requests.get(stream_url, stream=True, timeout=30)
    response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)

    client = sseclient.SSEClient(response)

    print(f"Connected to SSE stream: {stream_url}")
    for event in client.events():
        print(f"Event: id={event.id}, event={event.event}, data={event.data}")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →