Skip to main content

SSE plugin for Starlette

Project description

Server Sent Events for Starlette

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 the 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 the Request handler (see example.py):

async def endless(req: Request):
    async def event_publisher():
        i = 0
        while True:
            disconnected = await req.is_disconnected()
            if disconnected:
                _log.info(f"Disconnecting client {req.client}")
                break
            i += 1
            yield dict(data=i)
            await asyncio.sleep(0.2)
        _log.info(f"Disconnected from client {req.client}")

    return EventSourceResponse(event_publisher())

Run the tests:

make test

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

sse-starlette-0.3.3.tar.gz (5.1 kB view details)

Uploaded Source

File details

Details for the file sse-starlette-0.3.3.tar.gz.

File metadata

  • Download URL: sse-starlette-0.3.3.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.6.9

File hashes

Hashes for sse-starlette-0.3.3.tar.gz
Algorithm Hash digest
SHA256 9071b269c8395f9868aacd70a99950caaf02ef6bacd58148250c0c788885fc37
MD5 f8350c21fd55bfddd711aeba04743d60
BLAKE2b-256 c4050d5294f5c4df4a2ae2e14217cd1a47cedcfee02ac471028f2d17b5a705c9

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