Django 中的多个 HttpResponses
Multiple HttpResponses in Django
我有一个程序可以逐步打印数据。
例如:
data = {'a', 'b'}
for op in data:
if op == 'a':
print 'Hello'
elif op == 'b':
print 'Bye'
这是我的django项目中views.pyclass中的功能布局。每个打印语句都需要在浏览器上输出。我知道我可以使用单个响应
return HttpResponse('Hello')
或者只是
return Response('Hello')
如何实现多个输出?
您需要通过上下文传递一个列表,然后在模板中遍历该列表。例如:
views.py
def indexview(request):
data = []
for item in items_list:
data.append(item)
return render(request, 'index.html', {'data': data}
index.html
{% for item in data %}
{{ item }}
{% endfor %}
来自 HttpResponse 的 Django 文档:
...如果你想增量添加内容,你可以使用response作为类文件对象:
>>> response = HttpResponse()
>>> response.write("<p>Here's the text of the Web page.</p>")
>>> response.write("<p>Here's another paragraph.</p>")
https://docs.djangoproject.com/en/1.7/ref/request-response/#passing-strings
我想你想使用模板系统。 (参见 Hybrid 的回答)。
但是,您可以pass an iterator, instead of a string to HttpResponse
, and if necessary you can stream the results using, StreamingHttpResponse
。
def someview(request):
def mygen(data): # generator
for key, value in data.items():
yield value
data = {'a': 'Hello', 'b': 'Bye'}
g = mygen(data)
return StreamingHttpResponse(g)
我有一个程序可以逐步打印数据。
例如:
data = {'a', 'b'}
for op in data:
if op == 'a':
print 'Hello'
elif op == 'b':
print 'Bye'
这是我的django项目中views.pyclass中的功能布局。每个打印语句都需要在浏览器上输出。我知道我可以使用单个响应
return HttpResponse('Hello')
或者只是
return Response('Hello')
如何实现多个输出?
您需要通过上下文传递一个列表,然后在模板中遍历该列表。例如:
views.py
def indexview(request):
data = []
for item in items_list:
data.append(item)
return render(request, 'index.html', {'data': data}
index.html
{% for item in data %}
{{ item }}
{% endfor %}
来自 HttpResponse 的 Django 文档:
...如果你想增量添加内容,你可以使用response作为类文件对象:
>>> response = HttpResponse()
>>> response.write("<p>Here's the text of the Web page.</p>")
>>> response.write("<p>Here's another paragraph.</p>")
https://docs.djangoproject.com/en/1.7/ref/request-response/#passing-strings
我想你想使用模板系统。 (参见 Hybrid 的回答)。
但是,您可以pass an iterator, instead of a string to HttpResponse
, and if necessary you can stream the results using, StreamingHttpResponse
。
def someview(request):
def mygen(data): # generator
for key, value in data.items():
yield value
data = {'a': 'Hello', 'b': 'Bye'}
g = mygen(data)
return StreamingHttpResponse(g)