2016-07-14 44 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