Django 1.5 - 使用新的 StreamingHttpResponse [英] Django 1.5 - using the new StreamingHttpResponse

查看:15
本文介绍了Django 1.5 - 使用新的 StreamingHttpResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我实现 StreamingHttpResponse 如图所示此处,直到 10 秒结束后才会显示流式传输"响应.除了说它对于生成大型 CSV 文件很有用,同时警告说应该在请求-响应周期之外执行昂贵的任务.

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 />
'.format(x)
        time.sleep(1)

推荐答案

[OP 的解决方案转换为下面的答案]

[OP's solution converted to answer below]

Pavel 的评论指出我的例子的问题在于浏览器的缓冲,这是通过修改发送的数据量来解决的,例如

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)

这篇关于Django 1.5 - 使用新的 StreamingHttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆