sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
504 stars 35 forks source link

Question: can I store a reference to an SSE connection? #92

Closed ben-xD closed 1 month ago

ben-xD commented 3 months ago

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

sysid commented 1 month ago

No community response, closed due to inactivity.