Skip to main content

Server Sent Events for Starlette and FastAPI

PyPI Version Build Status Code Coverage

Background: https://sysid.github.io/sse/

Installation:

pip install sse-starlette

Usage:

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 dict(data=i)

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

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

app = Starlette(debug=True, routes=routes)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, log_level='info')

Output: output

Caveat: SSE streaming does not work in combination with GZipMiddleware.

Be aware that for proper server shutdown your application must stop all running tasks (generators). Otherwise you might experience the following warnings at shutdown: Waiting for background tasks to complete. (CTRL+C to force quit).

Client disconnects need to be handled in your Request handler (see example.py):

async def endless(req: Request):
    async def event_publisher():
        i = 0
        try:
          while True:
              i += 1
              yield dict(data=i)
              await asyncio.sleep(0.2)
        except asyncio.CancelledError as e:
          _log.info(f"Disconnected from client (via refresh/close) {req.client}")
          # Do any other cleanup, if any
          raise e
    return EventSourceResponse(event_publisher())

Run the tests:

make test

Special use cases

Fan out Proxies

Fan out proxies usually rely on response being cacheable. To support that, you can set the value of Cache-Control. For example:

return EventSourceResponse(
        generator(), headers={"Cache-Control": "public, max-age=29"}
    )

Changelog

1.1.3 (2022-07-26)

  • fix: py.typed was missing in PyPi distribution

1.1.0 (2022-07-25)

1.0.0 (2022-07-24)

  • drop support for python 3.6 and 3.7
  • removed unused private attribute _loop from class EventSourceResponse
  • updated example in README.md

0.10.3 (2022-01-25)

  • fix: use starlette's code to set proper content-type and charset
  • fix: update examples

0.10.0 (2021-12-14)

  • base EventSourceResponse on latest starlette StreamingResponse (0.17.1) and use anyio
  • breaking change: response.wait() and response.stop_streaming() removed

0.9.0 (2021-10-09)

  • add sse comment support

0.8.1 (2021-09-30)

  • minimum required python version relaxed to python 3.6

0.8.0 (2021-08-26)

  • using module-based logger instead of uvicorn logger

0.7.2 (2021-04-18)

  • refactoring: Github Actions introduced into build pipeline

0.6.2 (2020-12-19)

  • fix: correct shutdown signal handling in case of an endpoint which only yields sporadic messages

0.6.1 (2020-10-24)

  • updated example with proper error handling

0.6.0 (2020-10-24)

  • In case uvicorn is used: monkeypatch uvicorn signal-handler, in order to gracefully shutdown long-running handlers/generators.

Copyright © 2020, sysid. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Release files for sse-starlette 1.1.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 sse-starlette 1.1.4
File Size Uploaded
sse-starlette-1.1.4.tar.gz 9.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sse-starlette 1.1.4
File Interpreter ABI Platform
sse_starlette-1.1.4-py3-none-any.whl Python 3 none any Details

Total release size: 18.5 kB

Release files / sse-starlette-1.1.4.tar.gz

Download URL sse-starlette-1.1.4.tar.gz
Size 9.4 kB
Tags Source
SHA-256 checksum
How to use checksums
0d9dd32d64251578787abb5a30ca850524bf359d6bc0a574b3b238fdcac07412
BLAKE2b-256 checksum
How to use checksums
f8b57c057358e09940bd9c8ead3de7eed31b65d9c0a1c7847dc77a01902a52c5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.5

Release files / sse_starlette-1.1.4-py3-none-any.whl

Download URL sse_starlette-1.1.4-py3-none-any.whl
Size 9.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
55a166649ac9258e6564630891968b371b5616b30eb39d95abadec3709c091d0
BLAKE2b-256 checksum
How to use checksums
33d3c8f5660998b82268d144fdb3319973924e4c6bcb6aac0ba8b3d62ca621a4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.5

Release history Release notifications | RSS feed

3.4.9

2 release files

3.4.8

2 release files

3.4.7

2 release files

3.4.6

2 release files

3.4.5

2 release files

3.4.4

2 release files

3.4.3

2 release files

3.4.2

2 release files

3.4.1

2 release files

3.3.4

2 release files

3.3.3

2 release files

3.3.2

2 release files

3.3.1

2 release files

3.3.0

2 release files

3.2.1

2 release files

3.2.0

2 release files

3.1.2

2 release files

3.1.1

2 release files

3.1.0

2 release files

3.0.4

2 release files

3.0.3

2 release files

3.0.2

2 release files

3.0.1

2 release files

3.0.0

2 release files

2.4.1

2 release files

2.4.0

2 release files

2.3.6

2 release files

2.3.5

2 release files

2.3.4

2 release files

2.3.3

2 release files

2.3.2

2 release files

2.2.1

2 release files

2.2.0

2 release files

2.1.3

2 release files

2.1.2

2 release files

2.1.0

2 release files

2.0.0

2 release files

1.8.2

2 release files

1.8.1

2 release files

1.6.5

2 release files

1.6.4

2 release files

1.6.1

2 release files

1.6.0

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.4

2 release files

1.3.3

2 release files

1.2.1

2 release files

1.1.6

2 release files

This release

1.1.4 This release

2 release files

1.1.3

2 release files

1.1.2

2 release files

1.1.1

2 release files

1.1.0

2 release files

1.0.0

2 release files

0.10.3

2 release files

0.10.2

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.1

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.6.2

1 release file

0.6.1

1 release file

0.6.0

1 release file

0.5.2

1 release file

0.5.1

1 release file

0.5.0

1 release file

0.4.0

1 release file

0.3.4

1 release file

0.3.3

1 release file

0.3.2

1 release file

0.3.1

1 release file

0.3.0

1 release file

0.2.2

1 release file

0.2.1

1 release file

0.2.0

1 release file

0.1.0

1 release file

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