我对如何继续我的程序有点困惑。我有一个 django View ,要求用户输入名字和姓氏,然后这将转到处理数据并将其保存到数据库的 celery 任务。现在,当任务正在处理时,我希望显示一个动画 gif,以便用户知道发生了什么事。(我在这里的某个地方读过动画 gif 更好)然后如果任务完成,它将重定向到一个页面,告诉用户该过程已完成。我已经完成研究,发现我应该获取 task_id
并将其发送到 ajax 请求。
我的问题是如何使用ajax。如何从 ajax 获取 task_id?或者将 task_id 传递给 ajax 请求。
编辑: ** 我知道这是不完整的。非常不完整**
这是我的一些代码。它并没有做太多,因为我仍然必须掌握使用 ajax 的概念。但我想要的是当我提交表单时,会出现微调 gif,同时 celery 会处理我的任务。当 celery 完成任务处理后,它将重定向到一个页面,其中显示“成功”或任何内容。
views.py:
def addUser(request):
if request.method == 'POST':
addUser = userform(request.POST)
if addUser.is_valid():
task = create_user.apply_async((addUser.cleaned_data,), countdown=20)
return render_to_response('loading.html', {'task_id': task.task_id})
else:
addUser = userform()
return render(request, 'addUser.html', {'addUser':addUser})
addUser.html
<form method="POST">
{% csrf_token %}
{{ addUser }}
<input type="submit" value="Submit">
</form>
loading.html
<html>
<script>
<head>
<script src="{{ STATIC_URL }}js/jquery-ui.min.js"></script>
<script type="text/javascript">
var formData = task_id; // task id of my celery task
$.ajax({
url : "templates/success.html", //from what I know, this URL is where the AJAX will go after processing
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
alert("Success")
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("Failed")
}
});
</script>
</head>
<body><center>
{% load static %}
<img src="{% static 'images/ripple.gif' %}" alt="Hi!" height="150" width="150" />
</center>
</body>
</html>
tasks.py
@task(ignore_result=True)
def create_user(data):
user = UserInfo(fname=data['fname'], lname=data['lname'])
user.save()
return None
我不确定 AJAX 会去哪里,是在 form(addUser.html)
还是在 loading.html
如果我说错了请指正。感谢您的帮助!
最佳答案
想法是启动长时间运行的任务,当您执行一个任务时,它会返回一个 AsyncResult 对象,您必须获取“task_id”并将其返回给客户端。 客户端 (javascript) 将向/check_status/发出 GET 请求,并将“task_id”传递给服务器。 服务器将使用该 task_id 询问 celery,并返回给客户端任务是否完成。
def view_with_task(request):
#your code
# send the task to the worker and get the task_id
async_result = your_task.delay()
#code
ctx = {}
ctx['task_id'] = async_result.task_id
return render(tpl, ctx)
from celery import AsyncResult
def check_status(request):
task_id = request.GET.get('task_id')
if task_id:
async_result = AsyncResult(task_id)
return Jsonresponse({'finish': async_result.ready()})
return JsonResponse({'finish': False})
顺便说一句,有一个project这样做没有痛苦,也没有太多的代码。 谢谢
关于javascript - 将 Ajax 与 celery 任务一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31691040/