Django:在现有的HTML页面上返回StreamingHttpResponse [英] Django: return a StreamingHttpResponse on an existing html page

查看:702
本文介绍了Django:在现有的HTML页面上返回StreamingHttpResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于每个问题最好有一个问题,因此请耐心等待与与同一项目有关。

Since it is better to have a single question for each issue, be patient if is similar to another part of another my question related to the same project.

情况:

我在html上有一个表单,可以在其中设置一个数字,提交该表单时,它称为 views.stream_response 将值传递给 stream.py 并返回 StreamingHttpResponse ,然后出现虚拟空白浏览器页面( / stream_response / ),在该页面中,我可以每秒看到一个递增数,直到 m

I have a form on html in which I can set a number and when it is submitted, it is call views.stream_response which pass the value to stream.py and it returns a StreamingHttpResponse and "virtual" blank browser page appears (/stream_response/) in which I can see a progressive number every second up to m :

   1
   2
   3
   ..
   m

stream.py

import time

def streamx(m):
    lista = []
    x=0
    while len(lista) < m:      
        x = x + 1
        time.sleep(1)
        lista.append(x)
        yield "<div>%s</div>\n" % x 
        print(lista[-1])    
    return (x)

-更新-

views.py

def stream_response(request):   
    test = InputNumeroForm()   
    if request.method == 'POST':
        test = InputNumeroForm(data=request.POST)
        if test.is_valid():
            m = test.cleaned_data['numero']     
            print (test)      
            print("m = ", m) 
            #resp = StreamingHttpResponse(stream_response_generator(m))
            resp = StreamingHttpResponse(stream.streamx(m))
            return resp               
        return render(request, 'homepage/provadata.html',{'user.username': request, 'test': test}, context_instance = RequestContext(request))

urls.py

...
url(r'^homepage/provadata/$', views.provadata),    
url(r'^stream_response/$', views.stream_response, name='stream_response'),
...

homepage / provadata.html

<form  id="numero" action="/stream_response_bis/" method="POST">
    {% csrf_token %}
    {{test}}                                
    <input type="submit" value="to view" />
</form> 

//{{ris}} 

我尝试做render_to响应以留在 homepage / provadata.html 上并查看进度列表,但 stream.py 无法启动,我只能看到输入数字 m

I tried to do a render_to response to stay on homepage/provadata.html and to see the progressive lists but stream.py does not starts and I can see only the input number m on the command line.

我尝试了 views.py

def stream_response_generator(m):    
    ris = stream.streamx(m) 
    yield loader.get_template('homepage/provadata.html').render(Context({'ris': ris}))

(在模板中添加 {{ris}}

resp = StreamingHttpResponse(stream_response_generator(m)) stream_response 函数中)
但我在模板上获得了

(adding {{ris}} to template and
resp = StreamingHttpResponse(stream_response_generator(m)) in stream_response function) but I obtain on the template:

<生成器对象流为0x0000000004BEB870>

所以。如何解决此问题?

推荐答案

您可以使用StreamingHttpResponse表示要流回结果,并且django附带的所有中间件都知道这并采取相应措施以不缓冲您的内容输出,而是直接将其发送到该行。

You can use the StreamingHttpResponse to indicate that you want to stream results back and all the middleware that ships with django is aware of this and acts accordingly to not buffer your content output but send it straight down the line.

您可以使用条件装饰器禁用ETAG中间件。这将使您的响应通过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(), mimetype='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:在现有的HTML页面上返回StreamingHttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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