【问题标题】:Celery: How '|' operator works while chaining multi tasks?芹菜:如何'|'操作员在链接多个任务时工作?
【发布时间】:2016-07-14 00:18:10
【问题描述】:

我知道| 是一个按位“或”运算符,但这让我想知道它在 celery 的情况下如何工作,同时链接多个任务。

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

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

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

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

【问题讨论】:

    标签: python celery djcelery


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      他们很可能使用运算符重载为__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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-09
        • 2014-12-04
        • 2021-02-21
        • 1970-01-01
        • 2016-04-24
        • 1970-01-01
        • 2012-09-28
        • 2013-02-19
        相关资源
        最近更新 更多