gpt4 book ai didi

python - celery 异常处理

转载 作者:太空宇宙 更新时间:2023-11-03 10:53:31 25 4
gpt4 key购买 nike

假设我有这个任务定义:

def some_other_foo(input)
raise Exception('This is not handled!')
return input

@app.task(
bind=True,
max_retries=5,
soft_time_limit=20)
def some_foo(self, someInput={}):
response=""
try:
response = some_other_foo(someInput)
except Exception as exc:
self.retry(countdown=5, exc=exc)
response="error"
return response

我遇到一个问题,即 some_foo 中没有处理异常,我得到的是错误而不是 response="error",任务崩溃了,我得到的 Traceback 表明引发了异常。

是否可以返回常规响应,但将 celery 任务设置为失败,因此 flower 的结果将失败?

我正在使用:
celery 4.1
AMPQ作为经纪人
celery 花作为监控

最佳答案

尝试\except 工作正常。你的任务总是会失败,因为你在 return 之前调用了 self.retry。让我们做一个小测试:

from celery import Celery

app = Celery(name_app,broker_settings_etc....)

def some_other_foo(value):
raise Exception('This is not handled!')

@app.task(
bind=True,
max_retries=5,
soft_time_limit=20)
def some_foo(self):
response = ""

try:
response = some_other_foo('test')
except Exception as exc:
self.retry(countdown=5, exc=exc)
response = "error"

return response

运行 celery 应用程序并调用我们的任务。你会在 celery 日志中看到这样的东西:

3fb-81de-e4149fa88f4c] retry: Retry in 5s: Exception('This is not handled!',)
[2017-08-18 15:50:34,160: INFO/MainProcess] Received task: tasks.some_foo[b656731b-c85d-43fb-81de-e4149fa88f4c] eta:[2017-08-18 12:50:39.156912+00:00]
[2017-08-18 15:50:34,161: INFO/MainProcess] Task tasks.some_foo[b656731b-c85d-43fb-81de-e4149fa88f4c] retry: Retry in 5s: Exception('This is not handled!',)
[2017-08-18 15:50:39,511: ERROR/MainProcess] Task tasks.some_foo[b656731b-c85d-43fb-81de-e4149fa88f4c] raised unexpected: Exception('This is not handled!',)
Traceback (most recent call last):
# trace here...
Exception: This is not handled!

它是如何工作的。您为任务设置了 max_retries=5。当您调用 self.retry(countdown=5, exc=exc) 时,Celery 会中断任务处理并尝试使用 countdown(在我们的例子中 = 5)重新启动任务。 5 次尝试后 (max_retries) Celery 不会重新运行任务。

现在,让我们将 try\except block 更改为:

try:
response = some_other_foo('test')
except Exception:
print 'handled'
response = "bad response"

重启 Celery 并运行我们的任务。让我们检查日志:

[2017-08-18 15:58:41,893: INFO/MainProcess] Received task: tasks.some_foo[1437e7ce-1c69-4042-824b-5602f486c025]
[2017-08-18 15:58:41,895: WARNING/Worker-3] handled
[2017-08-18 15:58:41,896: INFO/MainProcess] Task tasks.some_foo[1437e7ce-1c69-4042-824b-5602f486c025] succeeded in 0.00186271299026s: 'bad response'

如您所见,处理程序工作正常。

所以,总结一下。如果调用 self.retry,Celery 将中断任务处理并尝试重新启动当前任务。

关于python - celery 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45611122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com