javascript - Celery+Django+jQuery -- Report success/failure of celery task in jQuery -


i asked similar question on how detect , report when celery task completed (or has failed). question focused on how using django messages framework, turned out unnecessary purposes. current approach send json httpresponse instead, , render success or failure message based on json received. below code poll state of task:

views.py:

def poll_state(request):     if request.is_ajax():         if 'task_id' in request.post.keys() , request.post['task_id']:             task_id = request.post['task_id']             task = asyncresult(task_id)             if task.successful():                 logger.debug("successful upload")                 return httpresponse(json.dumps({"message":"upload successful!", "state":"success"}), content_type='application/json')             elif task.failed():                 logger.debug("error in upload")                 return httpresponse(json.dumps({"message":"error in upload!", "state":"failure"}), content_type='application/json')         else:             logger.info('no task_id in request')     else:         logger.info('not ajax request')      result = task.result     state = task.state     response = {}     response["percent"] = result["percent"]     response["state"] = state     json_data = json.dumps(response)     return httpresponse(json_data, content_type='application/json') 

and corresponding jquery (and django templating):

{% if task_id %}     var pollstate = function(task_id) {         jquery.ajax({             url: "poll_state",             type: "post",             data: "task_id=" + task_id,         }).done(function(task) {             if (task.percent) {                 console.log(task.percent);                 jquery('.bar').css({'width': task.percent + '%'});                 jquery('.bar').html(task.percent + '%');             }             else if (task.state == "success" || task.state == "failure") {                 console.log(task.state);                 jquery('.status').html(task);             };             else {                 jquery('.status').html(task);             }             settimeout(function () {                 pollstate(task_id);             }, 300);         });     }     pollstate('{{ task_id }}'); {% endif %} 

and below code task itself:

tasks.py:

@task(base=dbtask) # custom base task class def upload_task(datapoints, user, description): # datapoints list of dictionaries, user , description strings     utils.db.databaseinserter import insertintodatabase     dp_count in insertintodatabase(datapoints, user, description): # insertintodatabase yields number of datapoints inserted database far @ end of each iteration         percent_completion = int(100 * (float(dp_count) / float(len(datapoints))))         current_task.update_state(state='progress', meta={'percent':percent_completion}) 

what happens if upload successful, once upload complete, console logs cluttered json success message. , if upload has error, reloading clutter logs error message. in both cases, poll_state continuously sending httpresponse of success or failure. additionally, after starting new task, still have old task info being sent rather current one. time current task info received first task when server first started; polling of subsequent tasks first task's info.

what doing wrong here? i've been scratching head @ while can't figure out. end goal here display sort of notification of completion of task or failure of task on web page, , not have success/failure httpresponse repeatedly sent after completion.

i've tried deleting task_id session key in task.successful() , task.failed() blocks in poll_state. prevent success/failure httpresponse being repeatedly sent, still have problem of subsequent tasks not having httpresponse sent; happens once new task started after first one, httpresponse first task sent, , percent tracking of current task no longer works.

after toil , struggle, turns out answer problems was, in fact, 1 single line.

the solution particular problem change

task_id = request.post['task_id'] 

to

task_id = request.session['task_id'] 

in poll_state.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -