Streaming responses with infinite iterators are consumed even after the client disconnects
Hello!
I have an HTTP endpoint that yields newline delimited JSON objects while the request is open, via Django's StreamingHttpResponse, like this:
def streaming_view(request):
streaming_content = infinite_generator()
return StreamingHttpResponse(streaming_content)
In well-behaved WSGI servers, like gunicorn, the iterator is interrupted and cleaned-up after the client disconnects, but with channels (via AsgiHandler) the iterator is consumed forever.
Even though I know long-running requests are not the intended usage of StreamingHttpResponse, I feel that this should be supported.
I patched the AsgiHandler with little effort to handle the ASGI message "http.disconnect" while the iterator is being consumed, and now it behaves correcly.
Do you think this is a valid bug? Should I submit a pull request? Thank you!
I concur. I use StreamingHttpResponse for long-running requests and Server-Side Events on the frontend. This is the easiest way (IMHO) to consume pure server-push events without having to use websockets.
Would you mind sharing the little patch to AsgiHandler you wrote ?
I've hit my head on this pretty hard and I could really use your code, hjalves