Django celery gets task status with Ajax

I use celery 2.5.3 and django celery - 2.5.5. And I use mysql as a broker.

Here is a scenario where a user request I queues a job for a worker who receives data from another site. And this may take several minutes depending on the size of the data. After starting the task, we should show the image of the bootloader. And when the employee finishes downloading the data (which will be in html format), I must replace the image of the bootloader with the received data.

The reason we use celery is because sometimes a script takes more than 30 seconds to finish and time.

I am currently planning to use the ajax call to check the status of the job, and this function will be used at fixed intervals.

I looked at a few questions, and that’s what I came up with

To start the worker, I use this code

def testCelery(request): result=testadd.apply_async() return HttpResponse(str(result.task_id)) 

This will return task_id on the client side and using ajax I will send a request to the server to check if the job is completed or not.

 def getStat(request,task_id): res = AsyncResult(task_id) s=res.ready() if s==True: return HttpResponse(str(res.get())) else: return HttpResponse(str(s)) 

I'm not sure if this is the right method or how it will behave in real time.

Please advice.

EDIT: view djcelery to check status

Ok, I changed my code as bruno suggested, and now it looks like

 from djcelery import views as celery_views def getStat(request,task_id): return celery_views.is_task_successful(request, task_id) 

And it looks like it works. And still using the ajax call with task_id to get the status.

+6
source share
1 answer

Django-celery already provides the views and URLs you are looking for - views.task_status and views.is_task_successful both take task_id as an argument and return a json response with (or) full status (including exception and trace if task failed) or just a boolean flag.

For example, add the following to urls.py :

 urlpatterns += patterns('djcelery.views', url(r'^task/status/(?P<task_id>.+)/$', 'task_status', name='task-status') ) 
+11
source

Source: https://habr.com/ru/post/920024/


All Articles