Django: return a StreamingHttpResponse on an existing html page

后端 未结 1 1505
一生所求
一生所求 2021-02-09 00:28

Since it is better to have a single question for each issue, be patient if is similar to another part of another my question related to the same project.

The situation:<

1条回答
  •  情歌与酒
    2021-02-09 01:09

    You can use the StreamingHttpResponse to indicate that you want to stream results back and all the middleware that ships with django is aware of this and acts accordingly to not buffer your content output but send it straight down the line.

    You can disable the ETAG middleware using the condition decorator. That will get your response to stream back over HTTP. You can confirm this with a command-line tool like curl. But it probably won't be enough to get your browser to show the response as it streams. To encourage the browser to show the response as it streams, you can push a bunch of whitespace down the pipe to force its buffers to fill. Example follows:

    from django.views.decorators.http import condition
    
    @condition(etag_func=None)
    def stream_response(request):
        resp = HttpResponse( stream_response_generator(), mimetype='text/html')
        return resp
    
    def stream_response_generator():
        yield "\n"
        for x in range(1,11):
            yield "
    %s
    \n" % x yield " " * 1024 # Encourage browser to render incrementally time.sleep(1) yield "\n"

    0 讨论(0)
提交回复
热议问题