Chrome不会从Django的StreamingHttpResponse中流式传输内容 [英] Chrome does not stream content from Django's StreamingHttpResponse

查看:49
本文介绍了Chrome不会从Django的StreamingHttpResponse中流式传输内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一年前,我使用Django的StreamingHttpResponse来流文本文件,然后Chrome立即显示它收到的每个文本块.现在,使用相同的代码,Chrome仅在完全加载文本文件时才显示文本,因此存在服务器超时的风险.Firefox不会发生这种情况.

A year ago, I used Django's StreamingHttpResponse to stream a text file and Chrome immediately displayed every chunk of text that it received. Now, with the same code, Chrome only displays the text when it completely loads the text file, thus risks server timeout. This does not happen with Firefox.

我创建了一个简单的测试:

I created a simple test:

# views.py
import time
from django.views import generic

class TestEditView(generic.TemplateView):
    def generator(self):
        for _ in range(15):
            time.sleep(1)
            yield 'THIS IS {}\n'.format(_)
            print('LOG: THIS IS {}\n'.format(_))

    def get(self, request, *args, **kwargs):
        return StreamingHttpResponse(self.generator(),
          content_type="text/plain; charset=utf-8")

如果我在Firefox中访问该视图,则该浏览器将每秒打印出"THIS IS ....",持续15秒钟.但是在Chrome浏览器中,浏览器将等待15秒钟,然后每秒打印出所有"THIS IS ...",即使开发服务器每秒记录一次"LOG:THIS IS ...".

If I access that view in Firefox, that browser will print out 'THIS IS ....' each second for 15 seconds. But in Chrome, the browser will wait 15 seconds, then print out all of the 'THIS IS...', even though the development server log 'LOG: THIS IS...' once a second.

我想知道我错过的这个问题是否有任何细微之处.谢谢.

I wonder if there is any subtlety in this problem that I missed. Thank you.

Python:3.6.2.
Django:1.10.5

Python: 3.6.2.
Django: 1.10.5

推荐答案

将content_type从"text/plain"更改为"text/html"或完全删除content_type即可解决此问题-Chrome使Chrome立即呈现每个文本块收到后.

Changing the content_type from "text/plain" to "text/html" or removing the content_type altogether solves the problem - it makes Chrome render each chunk of text immediately after it receives.

这篇关于Chrome不会从Django的StreamingHttpResponse中流式传输内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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