aiohttp-sse-client2

0.3.0 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates connecting to a public SSE stream and iterating over incoming events. It also includes basic error handling for common connection issues. For long-running connections, consider configuring `aiohttp.ClientTimeout` explicitly.

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())

view raw JSON →