芹菜:如何'|'操作员在链接多个任务时工作?

时间:2016-07-14 00:18:10

标签: python celery djcelery

我知道|是一个按位'或'运算符,但它让我想知道芹菜在链接多个任务时它是如何工作的。

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

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

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

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

2 个答案:

答案 0 :(得分:2)

如上所述,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

答案 1 :(得分:1)

他们可能会将运算符重载用作__or__(self, other)http://www.rafekettler.com/magicmethods.html

我不知道Celery的实施细节,只是为了给你一个想法:

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