SSE Client for Python
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
- gotcha When using `requests` with `sseclient-py`, you MUST pass `stream=True` to `requests.get()`. Failing to do so will cause `requests` to download the entire stream before `sseclient-py` can process any events, leading to memory issues and effectively blocking real-time processing.
- gotcha The `sseclient-py` library does not automatically handle reconnections or retries after a connection drops (e.g., due to network issues or server restart). Your application code needs to implement this logic for resilient SSE consumption.
- gotcha The library assumes the incoming data strictly adheres to the Server-Sent Events specification. Malformed or non-SSE data received from the server may lead to parsing errors, incomplete events, or unexpected behavior without clear warnings.
Install
-
pip install sseclient-py
Imports
- SSEClient
from sseclient import SSEClient
Quickstart
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}")