Skip to main content

Consume Server-Sent Event (SSE) messages with HTTPX.

Project description

httpx-sse

Build Status Coverage Package version

Consume Server-Sent Event (SSE) messages with HTTPX.

Table of contents

Installation

NOTE: This is beta software. Please be sure to pin your dependencies.

pip install httpx-sse=="0.3.*"

Quickstart

httpx-sse provides the connect_sse and aconnect_sse helpers for connecting to an SSE endpoint. The resulting EventSource object exposes the .iter_sse() and .aiter_sse() methods to iterate over the server-sent events.

Example usage:

import httpx
from httpx_sse import connect_sse

with httpx.Client() as client:
    with connect_sse(client, "GET", "http://localhost:8000/sse") as event_source:
        for sse in event_source.iter_sse():
            print(sse.event, sse.data, sse.id, sse.retry)

You can try this against this example Starlette server (credit):

# Requirements: pip install uvicorn starlette sse-starlette
import asyncio
import uvicorn
from starlette.applications import Starlette
from starlette.routing import Route
from sse_starlette.sse import EventSourceResponse

async def numbers(minimum, maximum):
    for i in range(minimum, maximum + 1):
        await asyncio.sleep(0.9)
        yield {"data": i}

async def sse(request):
    generator = numbers(1, 5)
    return EventSourceResponse(generator)

routes = [
    Route("/sse", endpoint=sse)
]

app = Starlette(routes=routes)

if __name__ == "__main__":
    uvicorn.run(app)

How-To

Calling into Python web apps

You can call into Python web apps with HTTPX and httpx-sse to test SSE endpoints directly.

Here's an example of calling into a Starlette ASGI app...

import asyncio

import httpx
from httpx_sse import aconnect_sse
from sse_starlette.sse import EventSourceResponse
from starlette.applications import Starlette
from starlette.routing import Route

async def auth_events(request):
    async def events():
        yield {
            "event": "login",
            "data": '{"user_id": "4135"}',
        }

    return EventSourceResponse(events())

app = Starlette(routes=[Route("/sse/auth/", endpoint=auth_events)])

async def main():
    async with httpx.AsyncClient(app=app) as client:
        async with aconnect_sse(
            client, "GET", "http://localhost:8000/sse/auth/"
        ) as event_source:
            events = [sse async for sse in event_source.aiter_sse()]
            (sse,) = events
            assert sse.event == "login"
            assert sse.json() == {"user_id": "4135"}

asyncio.run(main())

Handling reconnections

(Advanced)

SSETransport and AsyncSSETransport don't have reconnection built-in. This is because how to perform retries is generally dependent on your use case. As a result, if the connection breaks while attempting to read from the server, you will get an httpx.ReadError from iter_sse() (or aiter_sse()).

However, httpx-sse does allow implementing reconnection by using the Last-Event-ID and reconnection time (in milliseconds), exposed as sse.id and sse.retry respectively.

Here's how you might achieve this using stamina...

import time
from typing import Iterator

import httpx
from httpx_sse import connect_sse, ServerSentEvent
from stamina import retry

def iter_sse_retrying(client, method, url):
    last_event_id = ""
    reconnection_delay = 0.0

    # `stamina` will apply jitter and exponential backoff on top of
    # the `retry` reconnection delay sent by the server.
    @retry(on=httpx.ReadError)
    def _iter_sse():
        nonlocal last_event_id, reconnection_delay

        time.sleep(reconnection_delay)

        headers = {"Accept": "text/event-stream"}

        if last_event_id:
            headers["Last-Event-ID"] = last_event_id

        with connect_sse(client, method, url, headers=headers) as event_source:
            for sse in event_source.iter_sse():
                last_event_id = sse.id

                if sse.retry is not None:
                    reconnection_delay = sse.retry / 1000

                yield sse

    return _iter_sse()

Usage:

with httpx.Client() as client:
    for sse in iter_sse_retrying(client, "GET", "http://localhost:8000/sse"):
        print(sse.event, sse.data)

API Reference

connect_sse

def connect_sse(
    client: httpx.Client,
    method: str,
    url: Union[str, httpx.URL],
    **kwargs,
) -> ContextManager[EventSource]

Connect to an SSE endpoint and return an EventSource context manager.

This sets Cache-Control: no-store on the request, as per the SSE spec, as well as Accept: text/event-stream.

If the response Content-Type is not text/event-stream, this will raise an SSEError.

aconnect_sse

async def aconnect_sse(
    client: httpx.AsyncClient,
    method: str,
    url: Union[str, httpx.URL],
    **kwargs,
) -> AsyncContextManager[EventSource]

An async equivalent to connect_sse.

EventSource

def __init__(response: httpx.Response)

Helper for working with an SSE response.

response

The underlying httpx.Response.

iter_sse

def iter_sse() -> Iterator[ServerSentEvent]

Decode the response content and yield corresponding ServerSentEvent.

Example usage:

for sse in event_source.iter_sse():
    ...

aiter_sse

async def iter_sse() -> AsyncIterator[ServerSentEvent]

An async equivalent to iter_sse.

ServerSentEvent

Represents a server-sent event.

  • event: str - Defaults to "message".
  • data: str - Defaults to "".
  • id: str - Defaults to "".
  • retry: str | None - Defaults to None.

Methods:

  • json() -> Any - Returns sse.data decoded as JSON.

SSEError

An error that occurred while making a request to an SSE endpoint.

Parents:

  • httpx.TransportError

License

MIT

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog.

0.3.0 - 2023-04-27

Changed

  • Raising an SSEError if the response content type is not text/event-stream is now performed as part of iter_sse() / aiter_sse(), instead of connect_sse() / aconnect_sse(). This allows inspecting the response before iterating on server-sent events, such as checking for error responses. (Pull #12)

0.2.0 - 2023-03-27

Changed

  • connect_sse() and aconnect_sse() now require a method argument: connect_sse(client, "GET", "https://example.org"). This provides support for SSE requests with HTTP verbs other than GET. (Pull #7)

0.1.0 - 2023-02-05

Initial release

Added

  • Add connect_sse, aconnect_sse(), ServerSentEvent and SSEError.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

httpx-sse-0.3.0.tar.gz (11.9 kB view details)

Uploaded Source

Built Distribution

httpx_sse-0.3.0-py3-none-any.whl (7.5 kB view details)

Uploaded Python 3

File details

Details for the file httpx-sse-0.3.0.tar.gz.

File metadata

  • Download URL: httpx-sse-0.3.0.tar.gz
  • Upload date:
  • Size: 11.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.3

File hashes

Hashes for httpx-sse-0.3.0.tar.gz
Algorithm Hash digest
SHA256 a558b027ef3d04b0f744a242787cec585b44773979a92f0875b8a7e05cf51249
MD5 30db21bf687f07ae43cb65a138f713ab
BLAKE2b-256 5f53717056c553b7ff492dcffb32e5121f390f448eccf7fadf08deea1905b53c

See more details on using hashes here.

File details

Details for the file httpx_sse-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: httpx_sse-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 7.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.3

File hashes

Hashes for httpx_sse-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ff50c067ba7a0bae31416cf44cdc874127db4c3d4e1085159c85b3cc03b8e22c
MD5 47a898f5eadc809c71b6ea51b7e08d8e
BLAKE2b-256 8c481b52bda636267792453abe97c8518963ae19adc6fe29b8949120f9c6fc00

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page