A lot of django middleware will prevent streaming content. Most of this middleware should be included if you want to use the django admin application, so this can be annoying. Fortunately, this was allowed in the release of django 1.5 . You can use StreamingHttpResponse to indicate that you want to pass the results back, and all the middleware that comes with django is aware of this and acts accordingly not to buffer the output of your content, but to send it directly along the line. Then your code will look like this to use the new StreamingHttpResponse object.
def stream_response(request): return StreamingHttpResponse(stream_response_generator()) def stream_response_generator(): for x in range(1,11): yield "%s\n" % x
Apache Note
I tested above on Apache 2.2 with Ubuntu 13.04. The apache module mod_deflate, which was enabled by default in the test setup, will buffer the content you are trying to transfer until it reaches a certain block size, then it will gzip the content and send it to the browser. This will prevent the above example from working as desired. One way to avoid this is to disable mod_deflate by putting the following line in the apache configuration:
SetEnvIf Request_URI ^/mysite no-gzip=1
This is discussed in How to disable mod_deflate in apache2? question.
Marwan Alsabbagh Nov 17 '12 at 10:33 2012-11-17 10:33
source share