$ cat tips/django-streaminghttpresponse-gzip.md

Django StreamingHttpResponse not working: GZipMiddleware holds the stream

GZipMiddleware in Django 5.2 and 6.0 compresses a streaming response and keeps it in a buffer, so a short response reaches the browser whole, at the end. Set the Content-Encoding: identity header on the response and it goes out chunk by chunk.

Set the header in the view, before you return the response:

response = StreamingHttpResponse(words())
response["Content-Encoding"] = "identity"
return response

GZipMiddleware skips every response that already has a Content-Encoding header.

I ran into this with a chat that shows the model’s answer word by word. In the browser the whole answer appeared at once.

I measured it on a view that yields six words, one every half a second. With gzip two pieces arrived: the gzip header at once and all of the text after three seconds. With identity six pieces arrived, half a second apart.

The reason is in django.utils.text.compress_sequence. The function writes the chunks into the compressor and never flushes it, and the compressor gives data back only when it has a full block or when the stream ends.

Django 6.1 calls flush() there after every chunk (ticket #36293). The 5.2 and 6.0 branches do not have that call.

checked: Django 5.2.16, Python 3.13

$ ls ./blog/tips
all tips →
↑