Login

Django-Celery Progress Bar backend

Author:
fsfsfs
Posted:
February 28, 2013
Language:
Python
Version:
1.4
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months 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.