sse-starlette
sse-starlette copied to clipboard
Question: can I store a reference to an SSE connection?
I would like a reference to the SSE stream, so I can send messages to the user from anywhere else in my app. I would like to avoid using queues, polling or pubsub, as they seem a lot more complicated than storing a reference.
For example, when a user makes a request that returns an SSE stream, I would like to store that SSE stream somewhere (service.add_subscriber(sse)
)
This code won't work because EventSourceResponse
doesn't have a function to publish to the client. There is stream_response
, but that seems to be about starting the stream, not just adding arbitrary messages.
@router.get("/stream")
async def get_sensor_data_sse(request: Request, service: SensorDataService = Depends(SensorDataProvider.get)) -> EventSourceResponse:
async def remove_when_disconnected():
# remove when its done
if await request.is_disconnected():
service.remove_subscriber(sse_response)
sse_response = EventSourceResponse(remove_when_disconnected())
sevice.add_subscriber(sse_response)
return sse_response
Thoughts: Is this a limitation of the python model, where using that reference in a different context/thread would be very dangerous? So we really do need to use thread safe things like queues.
Thanks