Python Celery获取任务状态

t1qtbnec  于 2023-04-10  发布在  Python
关注(0)|答案(1)|浏览(370)

使用此代码并使用RabbitMQ设置Celery
任务被创建和执行。我得到了任务uuid,但不知何故不能检查任务状态

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)似乎无法获取任务状态。如何正确获取?

eimct9ow

eimct9ow1#

AsyncResult是一个对象,状态属性是你想要的:

@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"

备注:

1.任务也可能失败,因此有更好的方法来检查任务是否已执行(而不是与“SUCCESS”进行比较)。
1.如果你要添加celery应用程序,你不必使用特定的任务,这个函数可以帮助你通过uuid获取任何celery任务的状态。

@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"

相关问题