Skip to main content

Synchronous and asynchronous library for Server Sent Event (SSE).

Project description

drawing

ssec

ruff mypy gitmoji

Description

Python package for synchronous and asynchronous streaming of Server-Sent Events (SSE). This library works with httpx to support synchronous as well as asynchronous workflows but is also usable with other http frameworks (see below).

Installation

pip install ssec

Example

sync

import logging
import ssec

def main() -> None:
    logging.basicConfig(level=logging.INFO)
    for event in ssec.sse(
        "https://stream.wikimedia.org/v2/stream/recentchange"
    ):
        print(event)

main()

async

import asyncio
import logging
import ssec

async def main() -> None:
    logging.basicConfig(level=logging.INFO)
    async for event in ssec.sse_async(
        "https://stream.wikimedia.org/v2/stream/recentchange"
    ):
        print(event)

asyncio.run(main())

Note

Although there are already some libraries on the subject (aiohttp-sse-client, aiosseclient), these are unfortunately not entirely correct. In example, both mentioned libraries asynchronously iterate over the stream content via async for line in response.content[^1][^2]. This internally calls aiohttp's readuntil method with the default seperator \n, but the official specification says:

Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, a single U+000A LINE FEED (LF) character, or a single +000D CARRIAGE RETURN (CR) character.

Another point is the error handling, which is often not sufficient to analyze the error or is entirely skipped.

aiohttp

Although this library works with httpx, it is also possible to use it with other http frameworks like aiohttp as long as they provide a method to iterate over a byte-stream. Unfortunately, it is not possible to handle reconnection then, so you will have to implement that by yourself. An example could look like this:

import asyncio
import logging

import aiohttp
import ssec

async def main() -> None:
    logging.basicConfig(level=logging.INFO)

    chunk_size = 1024
    connect_attempt = 1
    max_connect_attempts = 5
    config = ssec.SSEConfig(reconnect_timeout=3)
    async with aiohttp.ClientSession() as session:
        while True:
            headers = {
                "Accept": "text/event-stream",
                "Cache-Control": "no-store",
            }
            if config.last_event_id:
                headers["Last-Event-ID"] = config.last_event_id
            try:
                async with session.get(
                    "https://stream.wikimedia.org/v2/stream/recentchange",
                ) as response:
                    streamer = response.content.iter_chunked(chunk_size)
                    async for event in ssec.stream_async(streamer, config=config):
                        print(event)
            except aiohttp.ClientError:
                if connect_attempt >= max_connect_attempts:
                    logging.exception("Failed to connect!")
                    raise

                waiting_period = config.reconnect_timeout

                message = (
                    f"Failed to connect. "
                    f"Reconnect in {waiting_period} seconds "
                    f"[attempt {connect_attempt}/{max_connect_attempts}]."
                )
                logging.info(message)

                connect_attempt += 1
                await asyncio.sleep(waiting_period)

asyncio.run(main())

[^1]: Code Reference
[^2]: Code Reference

Miscellaneous

Installation (Developer)

pip install ssec[dev]

Documentation

Build the documentation by running the following command in the root directory of the project:

sphinx-build -b html docs/src docs/build

The command requires the developers edition of ssec.

The documentation is then accessible via docs/build/index.html.

Set up Visual Studio Code for Development

To edit the code base with Visual Studio Code, you should install the @recommended extensions. Other necessary settings are already included in the .vscode directory and should be enabled by default.

Contributing

Contributing to ssec is highly appreciated, but comes with some requirements:

  1. Type Hints

    Write modern python code using type annotations to enable static analysis and potential runtime type checking.

  2. Documentation

    Write quality documentation using numpydoc docstring conventions.

  3. Linting

    Lint your code with ruff and mypy.

  4. Style

    Format your code using ruff.

  5. Testing

    Write tests for your code using pytest.

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

ssec-4.2.1.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ssec-4.2.1-py3-none-any.whl (10.5 kB view details)

Uploaded Python 3

File details

Details for the file ssec-4.2.1.tar.gz.

File metadata

  • Download URL: ssec-4.2.1.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for ssec-4.2.1.tar.gz
Algorithm Hash digest
SHA256 102bd8841d62b190061d1047b00bb8bbb0e83fd10e19d58bd9de3d13dfdad512
MD5 7b037a8076922deecbbf5b6a514d79d8
BLAKE2b-256 6131ade42e4f21f4a2f51b85e2355bbe5217f099464776f4dd500cd2717c991e

See more details on using hashes here.

File details

Details for the file ssec-4.2.1-py3-none-any.whl.

File metadata

  • Download URL: ssec-4.2.1-py3-none-any.whl
  • Upload date:
  • Size: 10.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for ssec-4.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e5da5f6703bb7e94e971133f0752d54ed7e12d7cb52cee6a03d1f9610c7f2bb0
MD5 022e3fbcd49f7efbdd2ff8be06bff59d
BLAKE2b-256 f5874855ebd5b8c27fe7ecac422ca7a53f083d326cccff0c092c14f211b767bf

See more details on using hashes here.

Supported by

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