由于每个问题最好只有一个问题,如果与我同一项目的另一部分相似,请耐心等待.
情况:
我在html上有一个表单,我可以在其中设置一个数字,当它被提交时,调用views.stream_response将值传递给stream.py并返回StreamingHttpResponse并显示"虚拟"空白浏览器页面(/ stream_response /),其中我可以每秒钟看到一个渐进的数字m:
1
2
3
..
m
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
--- UPDATE ---
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 …Run Code Online (Sandbox Code Playgroud) Django 1.5 刚刚发布并提供了 StreamingHttpResponse。现在,我已经阅读了这个讨论 ,第二个答案实际上在页面中打印出流(实际上只是数据)。
我想要做的是将流响应的输出打印到模板中,而不仅仅是像讨论中那样打印数据。
我该怎么办?我是否必须使用 javascript 并调用实现 StreamingHttpResponse 的视图,或者有一种方法可以告诉 django 呈现模板,然后将 StreamingHttpResponse 数据发送到模板(然后我需要知道存储数据的变量是什么) ?
编辑:到目前为止我发现的解决方案是将最终 html 页面的部分写入生成器(产量)。这个解决方案的问题是,例如,我不能有一个随着数据流而增长的条(如加载条)。
再见