2016-07-14 45 views
1

我知道|是一个按位“或”操作符,但它让我想知道如何在芹菜的情况下工作,而链接多个任务。芹菜:怎么'|'操作员在链接多任务时工作?

(first_task.s(url) | second_tasks.s()).apply_async() 

我知道,第二个任务将采取的第一个函数的结果作为ARGS但是这怎么可能? '|'在哪里在dj-celery源代码中重载?

@task 
def second_task(results): 
    do_something(results) 

有人可以提供一些见解吗?

回答

0

他们很可能会使用操作符重载为__or__(self, other)http://www.rafekettler.com/magicmethods.html

我不知道芹菜的实施细节,但只给你一个想法:

class Task(object): 
    def __init__(self, name): 
     self.name = name 
     self.chain = [self] 

    def __or__(self, other): 
     self.chain.append(other) 
     return self 

    def __repr__(self): 
     return self.name 

    def apply_async(self): 
     for c in self.chain: 
      print "applying", c 


(Task('A') | Task('B') | Task('C')).apply_async() 

输出:

applying A 
applying B 
applying C 
0

如上所述,Celery覆盖了__or__运营商,具体如下:

def __or__(self, other): 
    if isinstance(other, group): 
     other = maybe_unroll_group(other) 
    if not isinstance(self, chain) and isinstance(other, chain): 
     return chain((self,) + other.tasks, app=self._app) 
    elif isinstance(other, chain): 
     return chain(*self.tasks + other.tasks, app=self._app) 
    elif isinstance(other, Signature): 
     if isinstance(self, chain): 
      return chain(*self.tasks + (other,), app=self._app) 
     return chain(self, other, app=self._app) 
    return NotImplemented 

全面实施是在这里:https://github.com/celery/celery/blob/master/celery/canvas.py#L324