Django StreamingHttpResponse 到模板中 [英] Django StreamingHttpResponse into a Template
问题描述
Django 1.5 刚刚发布并提供了 StreamingHttpResponse.现在,我已经阅读了这个讨论和第二个答案打印出页面中的流(实际上只是数据).
Django 1.5 is just came out and it ships the StreamingHttpResponse. Now, I've read this discussion and the second answer actually prints out the stream in a page (actually just data).
我想要做的是将流响应的输出打印到模板中,而不仅仅是像 讨论.
What I want to do is to print the output of a stream response into a template, not just print the data as in the discussion.
我该怎么办?我是否必须使用 javascript 并调用实现 StreamingHttpResponse 的视图,或者有一种方法可以告诉 django 呈现模板,然后将 StreamingHttpResponse 数据发送到模板(然后我需要知道存储数据的变量是什么)?
What should I do? do I've to use javascript and call the view that implements the StreamingHttpResponse, or there's a way to tell django to render the template and later send the StreamingHttpResponse data to the template (then I need to know what's the variables where data are stored)?
目前我找到的解决方案是将最终 html 页面的片段写入生成器(yield).这个解决方案的问题是,例如,我不能有一个随着数据流而增长的条(如加载条).
the solution I found so far is to write the pieces of the final html page into the generator (yield). The problem of this solution is that I can't have, for example, a bar that grows with the data streamed (like a loading bar).
呸
推荐答案
是的,但它可能不是你真正想要的,因为整个模板都会被迭代.但是,无论如何,您可以为模板流式传输重新渲染的上下文.
Yes, but it may not be what you really want, as the entire template will be iterated. However, for what it's worth, you can stream a re-rendered context for a template.
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 />
')
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
编辑:你也可以渲染一个模板,然后在它上面附加 EDIT:
You can also render a template and just append 这篇关于Django StreamingHttpResponse 到模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 或
标签,但这与模板的初衷背道而驰.(即从代码中分离展示)
<p>
or <tr>
tags to it, but it's quite contrary to the purpose of templates in the first place. (i.e. separating presentation from code)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>{}
'.format(x, buffer)
登录
关闭