Python celery:如果有异常,则检索任务参数

Bor*_*jaX 9 python exception-handling celery

我开始使用Celery和Python,我有一个问题可能非常简单,但我似乎无法找到任何合适的答案......

如果我有一堆任务,并且其中一个抛出异常,是否有办法检索传递给所述任务的参数?

例如,如果我想获取一些主机名解析的IP,我创建一个任务......

@tasks_app.task
def resolve_hostname(hostname):
    return (hostname, {hst.address for hst in dns.resolver.query(hostname)})
Run Code Online (Sandbox Code Playgroud)

...可以抛出异常,是否有一种方法可以在hostname异常发生时将该参数的值置于调用之外?

假设我将任务分组如下:

ip_subtasks = group(
    resolve_hostname.s(hostname) for hostname in ['google.com',
                                                  'yahoo.com',
                                                  'failure.kommm']
)()
Run Code Online (Sandbox Code Playgroud)

最后一个(试图解决failure.kommm)将引发异常.我想get()将芹菜任务的方法放在一个try/catch,并在尝试解决failure.kommm(如下所示)显示一条消息说出现问题:

for ip_subtask in ip_subtasks:
    try:
        hostname, ips = ip_subtask.get(timeout=45)
    except dns.exception.DNSException, e:
        # I WISHED THIS WORKED:
        logger.exception("Something happened when trying"
                         " to resolve %s" % ip_subtask.args[0])
Run Code Online (Sandbox Code Playgroud)

所以,这就是问题......如果我有任务实例本身,有没有办法检索任务执行的参数?

先感谢您.

Nge*_*tor 10

为此,您可以使用抽象类来实现on_failure处理程序.

from celery import Task

class DebugTask(Task):
    abstract = True

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        logger.exception("Something happened when trying"
                         " to resolve %s" % args[0])

@tasks_app.task(base=DebugTask)
def resolve_hostname(hostname):
    return (hostname, {hst.address for hst in dns.resolver.query(hostname)})
Run Code Online (Sandbox Code Playgroud)

来自文档:

on_failure(self, exc, task_id, args, kwargs, einfo)

Parameters: 
  exc     – The exception raised by the task.
  task_id – Unique id of the failed task.
  args    – Original arguments for the task that failed.
  kwargs  – Original keyword arguments for the task that failed.
  einfo   – ExceptionInfo instance, containing the traceback.
Run Code Online (Sandbox Code Playgroud)