channels icon indicating copy to clipboard operation
channels copied to clipboard

Streaming responses with infinite iterators are consumed even after the client disconnects

Open hjalves opened this issue 5 years ago • 2 comments

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!

hjalves avatar Apr 19 '20 20:04 hjalves

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 ?

onekiloparsec avatar May 23 '20 12:05 onekiloparsec

I've hit my head on this pretty hard and I could really use your code, hjalves

icovada avatar Oct 06 '20 12:10 icovada