Server-sent events
rn_forge.fastapi.sse
Server-sent events over FastAPI.
Requires the sse extra. Not imported by :mod:rn_forge.fastapi.
Importing this module imports sse_starlette, which replaces
uvicorn.Server.handle_exit for the whole process so that open streams are
drained on shutdown (sse_starlette.sse.AppStatus).
:func:sse_response returns an EventSourceResponse; the media type, the
cache-control and x-accel-buffering headers, the heartbeat, disconnect
handling and graceful shutdown are its. This module adds validation of frame
fields, a terminal error frame, and a retry frame. It does not read
Last-Event-ID: the route does, and passes it to the event source.
DEFAULT_PING_SECONDS = 15.0
module-attribute
Seconds between heartbeat comments on an idle stream.
DEFAULT_RETRY_MS = 5000
module-attribute
Milliseconds a client waits before reconnecting a dropped stream.
sse_response(events, *, ping=DEFAULT_PING_SECONDS, retry=DEFAULT_RETRY_MS, registry=None, instance='', headers=None, log=None)
Stream events as text/event-stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
AsyncIterable[ServerSentEvent]
|
The frames to send, in order. |
required |
ping
|
float | None
|
Seconds between heartbeat comments while the stream is idle.
|
DEFAULT_PING_SECONDS
|
retry
|
int | None
|
Milliseconds a browser |
DEFAULT_RETRY_MS
|
registry
|
ProblemRegistry | None
|
Maps an exception escaping events to its problem. Defaults
to :func: |
None
|
instance
|
str
|
The problem's |
''
|
headers
|
Mapping[str, str] | None
|
Response headers. They are applied last, so each replaces a default of the same name. |
None
|
log
|
Log | None
|
Called as |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
EventSourceResponse
|
The response. Each frame of events is sent as given, except that an |
|
EventSourceResponse
|
|
|
with |
EventSourceResponse
|
class: |
EventSourceResponse
|
that one included, ends the stream with a single frame whose |
|
EventSourceResponse
|
is |
|
EventSourceResponse
|
|
|
EventSourceResponse
|
errors and send nothing. |
Raises:
| Type | Description |
|---|---|
ValueError
|
retry is not a non-negative integer, or ping is negative. |