Django 1.5 - using the new StreamingHttpResponse

北慕城南 提交于 2019-11-28 07:42:09

问题


If I implement StreamingHttpResponse as shown here, the 'streaming' response is not shown until the 10 seconds is up. There isn't much information on djangoproject except saying it's useful for generating large CSV files while warning that expensive tasks should be performed outside of the request-response cycle.

However, I cannot see that it is working at all using time-intensive code. Is there something about the generator object that prevents this? Here is the code duplicated for reference.

import time
from django.http import StreamingHttpResponse

def stream_response(request):
    resp = StreamingHttpResponse(stream_response_generator())
    return resp

def stream_response_generator():
    for x in range(1,11):
        yield '{} <br />\n'.format(x)
        time.sleep(1)

回答1:


[OP's solution converted to answer below]

Pavel's comment pointed out that the problem with my example was with the browser's buffering, which is solved by modifying the amount of data sent, as e.g.

yield '{} <br /> {}'.format(x, ' '*1024)


来源:https://stackoverflow.com/questions/15359768/django-1-5-using-the-new-streaminghttpresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!