2014-10-06 54 views
5

我開始使用芹菜和Python,我有一個問題可能很簡單,但我似乎無法找到任何合適的答案。Python芹菜:檢索任務的參數,如果有例外

如果我有一堆的任務,其中一個引發異常,是否有一種方法來檢索傳遞給所述任務的參數?

舉例來說,如果我想獲得一些主機名解析到IPS,以及創建一個任務...

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

...它可以拋出一個異常,有沒有得到的方式那個hostname參數的值在異常發生時的調用之外的值?

比方說,我喜歡小組的任務:

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

最後一個(即試圖解決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]) 

所以,這就是問題......如果我有任務實例本身,是否有一種方法可以檢索任務執行的參數?

預先感謝您。

+0

你有沒有看一個'on_failure'處理? http://celery.readthedocs.org/en/latest/userguide/tasks.html#on_failure – Ngenator 2014-10-06 20:33:16

+0

我有,我認爲它會工作,但我不知道如何使用它,當任務通過創建像上面顯示的裝飾器(正如我所說的,我是一個Celery的新手) – BorrajaX 2014-10-06 21:06:02

+0

查看上面的處理程序部分,它告訴你如何用抽象類來做到這一點。 – Ngenator 2014-10-06 21:16:02

回答

7

爲此,您可以使用abstract class來實施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)}) 

從文檔:

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.