Django StreamingHttpResponse成模板

时间:2013-02-27 16:14:01

标签: django templates stream

Django 1.5刚刚问世,它发布了StreamingHttpResponse。 现在,我已阅读this discussion,第二个答案实际上打印出页面中的流(实际上只是数据)。

我想要做的是将流响应的输出打印到模板中,而不是像the discussion中那样打印数据。

我该怎么办?我是否要使用javascript并调用实现StreamingHttpResponse的视图,或者有一种方法告诉django呈现模板,然后将StreamingHttpResponse数据发送到模板(然后我需要知道存储数据的变量是什么) ?

编辑:到目前为止我找到的解决方案是将最终的html页面的片段写入生成器(yield)。这个解决方案的问题在于,我不能拥有与数据流一起增长的条形图(如加载条)。

1 个答案:

答案 0 :(得分:4)

是的,但它可能不是您真正想要的,因为整个模板将被迭代。但是,对于它的价值,您可以为模板传输重新渲染的上下文。

from django.http import StreamingHttpResponse
from django.template import Context, Template

#    Template code parsed once upon creation, so
#        create in module scope for better performance

t = Template('{{ mydata }} <br />\n')

def gen_rendered():
    for x in range(1,11):
        c = Context({'mydata': x})
        yield t.render(c)

def stream_view(request):
    response = StreamingHttpResponse(gen_rendered())
    return response

修改: 您还可以渲染模板,只需向其添加<p><tr>标记,但这与模板的目的完全相反。 (即将演示文稿与代码分开)

from django.template import loader, Context
from django.http import StreamingHttpResponse

t = loader.get_template('admin/base_site.html') # or whatever
buffer = ' ' * 1024

def gen_rendered():  
    yield t.render(Context({'varname': 'some value', 'buffer': buffer}))
    #                                                 ^^^^^^
    #    embed that {{ buffer }} somewhere in your template 
    #        (unless it's already long enough) to force display

    for x in range(1,11):
        yield '<p>x = {}</p>{}\n'.format(x, buffer)