stop 未知任务 mysql_python – 从Celery中的’task_id’中检索未知任务的结果

在Celery中,当尝试从'task_id'检索一个未知任务的结果时,可能会遇到AttributeError。本文介绍了如何在不知道具体任务类型的情况下,正确地从数据库后端获取任务状态和结果。通过使用正确的AsyncResult初始化方式和指定正确的backend,可以成功获取任务状态,如'SUCCESSFUL',并获取任务结果。
摘要由CSDN通过智能技术生成

如果我以前不知道执行了哪个任务,如何提取任务结果?

这是设置:

给定以下源(‘tasks.py’):

from celery import Celery

app = Celery('tasks', backend="db+mysql://u:p@localhost/db", broker = 'amqp://guest:guest@localhost:5672//')

@app.task

def add(x,y):

return x + y

@app.task

def mul(x,y):

return x * y

RabbitMQ 3.3.2在本地运行:

marcs-mbp:sbin marcstreeter$./rabbitmq-server

RabbitMQ 3.3.2. Copyright (C) 2007-2014 GoPivotal, Inc.

## ## Licensed under the MPL. See http://www.rabbitmq.com/

## ##

########## Logs: /usr/local/var/log/rabbitmq/rabbit@localhost.log

###### ## /usr/local/var/log/rabbitmq/rabbit@localhost-sasl.log

##########

Starting broker... completed with 10 plugins.

与Celery 3.1.12在本地运行:

-------------- celery@Marcs-MacBook-Pro.local v3.1.12 (Cipater)

---- **** -----

--- * *** * -- Darwin-13.2.0-x86_64-i386-64bit

-- * - **** ---

- ** ---------- [config]

- ** ---------- .> app: tasks:0x105dea3d0

- ** ---------- .> transport: amqp://guest:**@localhost:5672//

- ** ---------- .> results: disabled

- *** --- * --- .> concurrency: 8 (prefork)

-- ******* ----

--- ***** ----- [queues]

-------------- .> celery exchange=celery(direct) key=celery

然后我可以导入方法并使用’task_id’检索结果:

from tasks import add, mul

from celery.result import AsyncResult

result = add.delay(2,2)

task_id = result.task_id

result.get() # 4

result = AsyncResult(id=task_id)

result.get() # 4

result = add.AsyncResult(id=task_id)

result.get() # 4

# and the same for the 'mul' task. Just imagine I put it here

在下一个示例中,我将在流程之间拆分这些步骤.在一个过程中,我像这样检索’task_id’:

from tasks import add

result = add.delay(5,5)

task_id = result.task_id

在另一个过程中,如果我使用相同的’task_id'(复制并粘贴到另一个REPL,或在不同的HTTP请求中),如下所示:

from celery.result import AsyncResult

result = AsyncResult(id="copied_task_id", backend="db+mysql://u:p@localhost/db")

result.get() # AttributeError: 'str' object has no attribute 'get_task_meta'

result.state # AttributeError: 'str' object has no attribute 'get_task_meta'

result.status # AttributeError: 'str' object has no attribute 'get_task_meta'

在另一个过程中,如果我这样做:

from task import add # in this instance I know that an add task was performed

result = add.AsyncResult(id="copied_task_id")

result.status # "SUCCESSFUL"

result.state # "SUCCESSFUL"

result.get() # 10

我希望能够在不知道什么任务产生结果的情况下获得结果.在我的真实环境中,我计划将此task_id返回给客户端,让他们通过HTTP请求查询其作业的状态.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值