aiohttp-sse-client

0.2.1 · maintenance · verified Thu Apr 16

aiohttp-sse-client is a Python client library for consuming Server-Sent Events (SSE) streams, built on top of `aiohttp`. It provides a simple asynchronous interface for connecting to SSE sources, processing incoming events, and handling automatic reconnections. The current version is 0.2.1, released in February 2021, indicating an infrequent release cadence. Note that a fork, `aiohttp-sse-client2`, exists to address maintenance and support newer Python versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates connecting to a public SSE stream and iterating over incoming events. It includes robust error handling for common connection issues and configures `aiohttp.ClientTimeout` for long-running connections to prevent premature timeouts.

import asyncio
import aiohttp
from aiohttp_sse_client import client as sse_client

async def listen_to_sse(url):
    session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None))
    try:
        async with sse_client.EventSource(url, session=session) as event_source:
            print(f"Connected to SSE stream at {url}")
            async for event in event_source:
                print(f"Event ID: {event.id}, Type: {event.type}, Data: {event.data}")
    except aiohttp.ClientConnectorError as e:
        print(f"Connection error: {e}")
    except ConnectionError as e:
        print(f"Stream disconnected: {e}")
    except asyncio.TimeoutError:
        print("SSE stream timed out. Ensure server sends keep-alives or configure ClientTimeout.")
    finally:
        await session.close()

async def main():
    # Example public SSE stream (e.g., Wikimedia recent changes)
    sse_url = "https://stream.wikimedia.org/v2/stream/recentchange"
    await listen_to_sse(sse_url)

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →