每隔几秒更新一次 HttpResponse [英] Update HttpResponse Every Few Seconds
问题描述
我在 Django 中的应用程序可以创建一些 非常 大的 SQL 查询.我目前使用 HttpRequest
对象来获取我需要的数据,然后使用 HttpResponse
来返回我想要显示给用户的内容.
My application in Django can create some very big SQL queries. I currently use a HttpRequest
object, for the data I need, then a HttpResponse
, to return what I want to show the User.
显然,我可以让用户等待一分钟,同时执行这些多组查询并从数据库中提取,然后返回这个单一的 HTML 页面.
Obviously, I can let the User wait for a minute whilst these many sets of queries are being executed and extracted from the database, then return this monolothic HTML page.
理想情况下,我想在需要时更新页面,例如:
Ideally, I'd like to update the page when I want, something like:
For i,e in enumerate(example):
Table.objects.filter(someObjectForFilter[i]).
#Return the object to the page.
#Then Loop again, 'updating' the response after each iteration.
这可能吗?
推荐答案
我最近发现一个HttpResponse可以是一个生成器:
I discovered recently that an HttpResponse can be a generator:
def myview(request, params):
return HttpResponse(mygenerator(params))
def mygenerator(params):
for i,e in enumerate(params):
yield '<li>%s</li>' % Table.objects.filter(someObjectForFilter[i])
这将逐步将 mygenerator
的结果返回到页面,并以 HTML <li>
进行显示.
This will progressively return the results of mygenerator
to the page, wrapped in an HTML <li>
for display.
这篇关于每隔几秒更新一次 HttpResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!