pythonfastapistarletteasgi

how to decide if StreamingResponse was closed in FastAPI/Starlette?


When looping a generator in StreamingResponse() using FastAPI/starlette

https://www.starlette.io/responses/#streamingresponse

how can we tell if the connection was somehow disconnected, so a event could be fired and handled somewhere else?

Scenario: writing an API with text/event-stream, need to know when client closed the connection.


Solution

  • Consider using request.is_disconnected(). From Starlette's docs:

    In some cases such as long-polling, or streaming responses you might need to determine if the client has dropped the connection. You can determine this state with disconnected = await request.is_disconnected().

    Unfortunately, there seems to be no other documentation regarding this API. Have a look at the MR that introduced this feature: https://github.com/encode/starlette/pull/320