Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django celery retrieve task status using Ajax

I'm using celery 2.5.3 and django celery - 2.5.5. And I'm using mysql as the broker.

Here is the scenario, when the user request i queue a job in the worker which is getting data from another site. And this may take few minutes depending upon the size of the data. Once the job is started we have to show a loader image. And when worker finishes downloading data (which will be in html format) i have to replace the loader image with data retrieved.

The reason we are using celery is that sometimes script takes more than 30 second to finish and timesout.

Currently I'm planning to use an ajax call to check the status of job and this function will be used at fixed intervals.

I have gone through few question, and this is what I came up with

To start the worker, I'm using this code

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

This will return the task_id to the client side and using ajax i will send request to the server to check if the job has finished 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 will it behave in a real time scenario.

Please advice.

EDIT : using djcelery view to check the status

Ok i have modified my code as bruno suggested and now its looks like

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

And its seems to be working. And still using an ajax call with the task_id to retrieve the status.

like image 967
Nick Avatar asked Jul 09 '12 10:07

Nick


1 Answers

Django-celery already provides the views and urls you're looking for - views.task_status and views.is_task_successful both take the task_id as argument and return a json response with (resp.) the full status (including exception and traceback 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')
)
like image 163
bruno desthuilliers Avatar answered Sep 21 '22 01:09

bruno desthuilliers