如何使用 Django 流式传输 HttpResponse [英] How to stream an HttpResponse with Django

查看:40
本文介绍了如何使用 Django 流式传输 HttpResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 Django (1.2) 获取流式响应的hello world".我想出了如何使用生成器和 yield 函数.但是响应仍然没有流式传输.我怀疑有一个中间件在处理它——也许是 ETAG 计算器?但我不确定如何禁用它.有人可以帮忙吗?

这是我到目前为止的hello world"流媒体:

def stream_response(request):resp = HttpResponse(stream_response_generator())返回响应def stream_response_generator():对于范围内的 x(1,11):yield "%s
" % x # 向浏览器返回一段响应时间.sleep(1)

解决方案

您可以使用 条件装饰器.这将使您的响应通过 HTTP 流回.您可以使用像 curl 这样的命令行工具来确认这一点.但这可能不足以让您的浏览器在流式传输时显示响应.为了鼓励浏览器在响应流时显示响应,您可以将一堆空格向下推入管道以强制填充其缓冲区.示例如下:

from django.views.decorators.http 导入条件@condition(etag_func=None)定义流响应(请求):resp = HttpResponse(stream_response_generator(), content_type='text/html')返回响应def stream_response_generator():产量 "
"对于范围内的 x(1,11):产量 "

%s

" % xyield " " * 1024 # 鼓励浏览器增量渲染时间.sleep(1)产生</body></html> "

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?

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
" % x  # Returns a chunk of the response to the browser
        time.sleep(1)

解决方案

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>
"
    for x in range(1,11):
        yield "<div>%s</div>
" % x
        yield " " * 1024  # Encourage browser to render incrementally
        time.sleep(1)
    yield "</body></html>
"

这篇关于如何使用 Django 流式传输 HttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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