Giter VIP home page Giter VIP logo

sse-starlette's Introduction

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:
              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}")
        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

Changelog

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.

sse-starlette's People

Contributors

sysid avatar synodriver avatar alairock avatar cyprienc avatar havardthom avatar vaibhavmule avatar justindujardin avatar nekonoshiri avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.