如何使用Django流式传输HttpResponse [英] How to stream an HttpResponse with Django
问题描述
我正在尝试让Django(1.2)工作的流式响应的hello world。我想出了如何使用发电机和 yield
函数。但是响应仍然没有流媒体。我怀疑有一个中间件,它是捣蛋 - 也许ETAG计算器?但我不知道如何禁用它。有人可以帮忙吗?
I'm trying to get the 'hello world' of streaming responses working for Django (1.2). I figured out how to use a generator and the yield
function. But the response still not streaming. I suspect there's a middleware that's mucking with it -- maybe ETAG calculator? But I'm not sure how to disable it. Can somebody please help?
这是我到目前为止的流媒体的hello world:
Here's the "hello world" of streaming that I have so far:
def stream_response(request):
resp = HttpResponse( stream_response_generator())
return resp
def stream_response_generator():
for x in range(1,11):
yield "%s\n" % x # Returns a chunk of the response to the browser
time.sleep(1)
推荐答案
您可以使用条件装饰器。这将使您的响应通过HTTP流回。您可以使用命令行工具(如 curl
)进行确认。但是,它可能不足以让您的浏览器显示响应流。为了鼓励浏览器在响应流时显示响应,您可以在管道下方拖动一堆空白,以强制缓冲区填充。示例如下:
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(), content_type='text/html')
return resp
def stream_response_generator():
yield "<html><body>\n"
for x in range(1,11):
yield "<div>%s</div>\n" % x
yield " " * 1024 # Encourage browser to render incrementally
time.sleep(1)
yield "</body></html>\n"
这篇关于如何使用Django流式传输HttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!