featherweight.sse¶
sse ¶
Server-sent events: the one way featherweight streams job events to a client.
encode turns the stream of a job's events (job_events) into SSE text, and HEADERS are the headers of the response. There is
no server here: your API sends the response (a StreamingResponse in FastAPI). id is the sequence number of the event, so a
browser that reconnects sends Last-Event-ID and the stream resumes after it.
@app.get("/jobs/{job_id}/events")
async def events(job_id: str, request: Request):
after = int(request.headers.get("last-event-id", 0))
return StreamingResponse(sse.encode(job_events(db, job_id, after)), headers=sse.HEADERS)
format_event ¶
format_event(event: JobEvent) -> str
One event as SSE: id, event (its type) and data (JSON, compact).
encode
async
¶
encode(
events: AsyncIterator[JobEvent],
*,
keep_alive: float = 15.0,
) -> AsyncGenerator[str, None]
The events as SSE text. A comment line goes out every keep_alive seconds while nothing arrives, to keep the connection
open. The stream ends when the events end, and closes the source when the consumer stops.