Skip to main content

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

Usage

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

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.

  1. Code Reference ↩

  2. Code Reference ↩

Metadata

Release files for ssec 4.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ssec 4.2.4
File Size Uploaded
ssec-4.2.4.tar.gz 11.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for ssec 4.2.4
File Interpreter ABI Platform
ssec-4.2.4-py3-none-any.whl Python 3 none any Details

Total release size: 21.9 kB

Release files / ssec-4.2.4.tar.gz

Download URL ssec-4.2.4.tar.gz
Size 11.5 kB
Tags Source
SHA-256 checksum
How to use checksums
66455d512b54e83102cc6b8ce53a0b1c634a7c8ba3e4faaa87505d7f478720ab
BLAKE2b-256 checksum
How to use checksums
1265b0e14cc4e82a30ee90ef4f85fd8b3e266687090ab343418d66da88368270
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.3

Release files / ssec-4.2.4-py3-none-any.whl

Download URL ssec-4.2.4-py3-none-any.whl
Size 10.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3b11038e8e1a00e3c7508e6ff616a6bb08504435b6358efe81312b12955a5b65
BLAKE2b-256 checksum
How to use checksums
c52a3ee5ec22861be3a9bd3467d7974240f987ea998d31e967f1fd7861243417
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.3

Release history Release notifications | RSS feed

This release

4.2.4 This release

2 release files

4.2.3

2 release files

4.2.2

2 release files

4.2.1

2 release files

4.2.0

2 release files

4.1.0

2 release files

4.0.1

2 release files

4.0.0

2 release files

3.0.2

2 release files

3.0.1

2 release files

3.0.0

2 release files

2.0.0

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page