Login

Django-Celery Progress Bar backend

Author:
fsfsfs
Posted:
February 28, 2013
Language:
Python
Version:
1.4
Tags:
progress celery
Score:
0 (after 0 ratings)

This is my POC code for a progress bar backend (for delivering JSON to some AJAX frontend) in Django using Django-Celery (with RabbitMQ). It is quite concise, yet it took me a while to get there because Celery's Documentation is IMHO rather puristic. Web development is meant to be copy-paste! Here you go!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from time import sleep

from celery import task, current_task
from celery.result import AsyncResult

from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.utils import simplejson as json
from django.conf.urls import patterns, url


@task()
def do_work():
    """ Get some rest, asynchronously, and update the state all the time """
    for i in range(100):
        sleep(0.1)
        current_task.update_state(state='PROGRESS',
            meta={'current': i, 'total': 100})


def poll_state(request):
    """ A view to report the progress to the user """
    if 'job' in request.GET:
        job_id = request.GET['job']
    else:
        return HttpResponse('No job id given.')

    job = AsyncResult(job_id)
    data = job.result or job.state
    return HttpResponse(json.dumps(data), mimetype='application/json')


def init_work(request):
    """ A view to start a background job and redirect to the status page """
    job = do_work.delay()
    return HttpResponseRedirect(reverse('poll_state') + '?job=' + job.id)


urlpatterns = patterns('webapp.modules.asynctasks.progress_bar_demo',
    url(r'^init_work$', init_work),
    url(r'^poll_state$', poll_state, name="poll_state"),
)

More like this

  1. Serialize a model instance by chriswedgwood 1 week ago
  2. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 9 months, 1 week ago
  3. Crispy Form by sourabhsinha396 10 months ago
  4. ReadOnlySelect by mkoistinen 10 months, 2 weeks ago
  5. Verify events sent to your webhook endpoints by santos22 11 months, 1 week ago

Comments

weswinham (on March 1, 2013):

If you'd like to some more help with progress calculation, updating and other goodies, check out jobtastic.

#

endur (on August 28, 2014):

Thanks So much.This has really help me a lot. I've succeeded in tracking and displaying results to users for a long running celery task.

#

Please login first before commenting.