Python Celery get task status

Question:

Have this code and setup Celery with RabbitMQ

Tasks get created and executed. I get task uuid,but somehow cannot check task statuses

from flask_oidc import OpenIDConnect
from flask import Flask, json, g, request
from flask_cors import CORS
from celery import Celery
import os
import time


app = Flask(__name__)
app.config.update({
  'OIDC_CLIENT_SECRETS': './client_secrets.json',
  'OIDC_RESOURCE_SERVER_ONLY': True,
  'CELERY_BROKER_URL': 'amqp://rabbitmq:rabbitmq@rabbit:5672/',
  'CELERY_RESULT_BACKEND': 'rpc://'
})
oidc = OpenIDConnect(app)
CORS(app)

client = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
client.conf.update(app.config)



@client.task()
def removeUser(id):
  time.sleep(10);


@app.route("/removeUser", methods=['GET'])
def removeUserID():
  id = request.args.get('id')
  result = removeUser.apply_async(args=[id], countdown=60)
  return result.id
  

@app.route("/checkStatus", methods=['GET'])
def checkStatus():
  uuid = request.args.get('uuid') 
  res = removeUser.AsyncResult(uuid)
  print(uuid)
  if(res=="SUCCESS"):
    return "success"
  else:
    return "progress"

def json_response(payload, status=200):
  return (json.dumps(payload), status, {'content-type': 'application/json'})

res = removeUser.AsyncResult(uuid) does not seem to get task status. How to get it correctly?

Asked By: dev

||

Answers:

AsyncResult is an object and state property is what you want:

@app.route("/checkStatus", methods=['GET'])
def checkStatus():
  uuid = request.args.get('uuid') 
  res = removeUser.AsyncResult(uuid)
  print(uuid)
  if res.state == "SUCCESS":
    return "success"
  else:
    return "progress"

Notes:

  1. Task might fail as well so that there’s a better way to check if the task has executed (rather than compare to "SUCCESS").
  2. If you’ll add the celery app you don’t have to use a specific task and this function can help you to get the state of any celery task by uuid.
@app.route("/checkStatus", methods=['GET'])
def checkStatus():
  uuid = request.args.get('uuid') 
  res = AsyncResult(uuid, app=client)
  print(uuid)
  if res.ready():
    return "success"
  else:
    return "progress"
Answered By: ItayB
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.