SSE plugin for Starlette
Project description
Server Sent Events for Starlette and FastAPI
Implements the Server-Sent Events specification.
Background: https://sysid.github.io/server-sent-events/
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:
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())
Special use cases
Customize Ping
By default, the server sends a ping every 15 seconds. You can customize this by:
- setting the
ping
parameter - by changing the
ping
event to a comment event so that it is not visible to the client
@router.get("")
async def handle():
generator = numbers(1, 100)
return EventSourceResponse(
generator,
headers={"Server": "nini"},
ping=5,
ping_message_factory=lambda: ServerSentEvent(**{"comment": "You can't see\r\nthis ping"}),
)
SSE Send Timeout
To avoid 'hanging' connections in case HTTP connection from a certain client was kept open, but the client stopped reading from the connection you can specifiy a send timeout (see #89).
EventSourceResponse(..., send_timeout=5) # terminate hanging send call after 5s
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"}
)
Error Handling
See example: examples/error_handling.py
Sending Responses without Async Generators
Async generators can expose tricky error and cleanup behavior especially when they are interrupted.
Background: Cleanup in async generators.
Example no_async_generators.py
shows an alternative implementation
that does not rely on async generators but instead uses memory channels (examples/no_async_generators.py
).
Development, Contributing
- install pdm:
pip install pdm
- install dependencies using pipenv:
pdm install -d
. - To run tests:
Makefile
- make sure your virtualenv is active
- check
Makefile
for available commands and development support, e.g. run the unit tests:
make test
make tox
For integration testing you can use the provided examples in tests
and examples
.
If you are using Postman, please see: https://github.com/sysid/sse-starlette/issues/47#issuecomment-1445953826
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file sse_starlette-2.1.3.tar.gz
.
File metadata
- Download URL: sse_starlette-2.1.3.tar.gz
- Upload date:
- Size: 19.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: pdm/2.15.4 CPython/3.12.2 Darwin/23.4.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9cd27eb35319e1414e3d2558ee7414487f9529ce3b3cf9b21434fd110e017169 |
|
MD5 | 7ed3e07a7580f56d0683ea2c20be3e8b |
|
BLAKE2b-256 | 72fc56ab9f116b2133521f532fce8d03194cf04dcac25f583cf3d839be4c0496 |
File details
Details for the file sse_starlette-2.1.3-py3-none-any.whl
.
File metadata
- Download URL: sse_starlette-2.1.3-py3-none-any.whl
- Upload date:
- Size: 9.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: pdm/2.15.4 CPython/3.12.2 Darwin/23.4.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8ec846438b4665b9e8c560fcdea6bc8081a3abf7942faa95e5a744999d219772 |
|
MD5 | 98c91b2a06d24a27123f22d72916a6f0 |
|
BLAKE2b-256 | 52aa36b271bc4fa1d2796311ee7c7283a3a1c348bad426d37293609ca4300eef |