Python + Celery:链接工作?

发布于 2021-01-29 17:55:32

芹菜文件表明,这是一个坏主意,有任务等待的其他任务的结果。但建议的解决方案(见“好”的标题)离开是可喜爱的东西。具体来说,没有明确的方法可以将子任务的结果返回给调用者(同样,这很丑陋)。

那么,有什么方法可以“链接”工作,以便呼叫者获得最终工作的结果?例如,使用add示例:

>>> add3 = add.subtask(args=(3, ))
>>> add.delay(1, 2, callback=add3).get()
6

或者,可以返回Result实例吗?例如:

@task
def add(x, y, callback=None):
    result = x + y
    if callback:
        return subtask(callback).delay(result)
    return result

这样就可以通过简单的方法检索链中“最终”工作的结果:

result = add(1, 2, callback=add3).delay()
while isinstance(result, Result):
    result = result.get()
print "result:", result
关注者
0
被浏览
40
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以用芹菜链来做。参见https://celery.readthedocs.org/en/latest/userguide/canvas.html#chains

    @task()
    def add(a, b):
        time.sleep(5) # simulate long time processing
        return a + b
    

    链接工作:

    # import chain from celery import chain
    # the result of the first add job will be 
    # the first argument of the second add job
    ret = chain(add.s(1, 2), add.s(3)).apply_async()
    
    # another way to express a chain using pipes
    ret2 = (add.s(1, 2) | add.s(3)).apply_async()
    
    ...
    
    # check ret status to get result
    if ret.status == u'SUCCESS':
        print "result:", ret.get()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看