aiohttp-sse-client2
aiohttp-sse-client2 is a Python client library for Server-Sent Events (SSE) built on top of aiohttp, providing a straightforward interface for consuming event streams. It is a fork of the original `aiohttp-sse-client` project, featuring improved error messages and updated compatibility with newer Python versions. The current version is 0.3.0, released in February 2023, indicating an infrequent release cadence.
Warnings
- breaking Python version support has changed between major versions. Version 0.2.0 dropped support for Python 3.5, and version 0.3.0 dropped support for Python 3.6.
- gotcha The underlying `aiohttp.ClientSession` used by `EventSource` has a default total timeout (typically 5 minutes). For long-lived SSE connections, this can lead to `asyncio.TimeoutError` or `ClientOSError: [Errno 104] Connection reset by peer` even with server-side keep-alives.
- gotcha This library is a fork of `aiohttp-sse-client`, and its long-term maintenance is conditional: 'The fork will be retired if the upstream package comes back alive.'
- gotcha Asynchronous network operations are inherently prone to disconnections. The quickstart example explicitly includes `except ConnectionError: pass`, indicating that connection failures are common and client applications should implement robust error handling and reconnection logic.
Install
-
pip install aiohttp-sse-client2
Imports
- EventSource
from aiohttp_sse_client2 import client as sse_client # then use sse_client.EventSource
Quickstart
import asyncio
from aiohttp_sse_client2 import client as sse_client
async def main():
# Replace with your SSE endpoint
sse_url = "https://stream.wikimedia.org/v2/stream/recentchange"
# It's recommended to pass an aiohttp.ClientSession with a custom timeout
# if long-lived connections are expected (e.g., timeout=aiohttp.ClientTimeout(total=None))
# For this quickstart, we'll use the default behavior.
async with sse_client.EventSource(sse_url) as event_source:
try:
async for event in event_source:
print(f"Received event: {event.id} - {event.event} - {event.data}")
except ConnectionError:
print("Connection closed unexpectedly or failed to establish.")
except asyncio.TimeoutError:
print("Connection timed out.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
asyncio.run(main())