【发布时间】:2014-09-08 16:03:13
【问题描述】:
所以我想知道完成以下任务的最佳实践:
def execute_expensive_operation(obj):
#create instance of a model storing the relevant info to load the JSON into the template
#includea `task` field that stores the name of the asynchronous task (obj.pk) so that the JSON can be loaded if the name of the task is known
def test_view(request):
list_of_objects = [...] #will actually be dynamically loaded from the request
task_dict = {}
for obj in list_of_objects:
task_dict[obj.pk] = execute_expensive_operation(obj).delay(obj.pk) #this could take a while, put it on queue (using celery)
context = {"tasks":task_dict}
return render_to_response("template.html",context)
"template.html" 将加载与表中一行中的每个 obj 相关的 JSON
正如上面设置的那样,task_dict 实际上将填充AsyncResult 对象而不是 JSON。我想要做的是在与该行相关的异步任务完成后动态加载任何行。
注意:
对于非特定方法,我深表歉意,这不是针对任何特定的东西,而是对于我必须在各种不同地方处理的一般情况更是如此。如果有任何遗漏的信息,请告诉我,以便我补充。
【问题讨论】:
-
我认为你不能在前端使用
AsyncResult来更新结果。您可以发送 ajax 请求并获取结果。 -
对,所以我可以使用 Ajax 根据 AsyncResult 的名称进行获取,但问题是我什么时候调用 Ajax?我如何从模板中知道任务何时完成并且有信息要加载?
-
您可以根据完成工作所需的时间,定期自动发送 ajax 请求。
-
好的,听起来好像可以。谢谢!