【问题标题】:Celery: Chaining tasks with multiple argumentsCelery:使用多个参数链接任务
【发布时间】:2013-01-18 09:51:21
【问题描述】:

celery 文档告诉我,如果多个任务链接在一起,第一个任务的结果将是下一个任务的第一个参数。我的问题是,当我有一个返回多个结果的任务时,我无法让它工作。

例子:

@task()
def get_comments(url):
    #get the comments and the submission and return them as 2 objects
    return comments, submission

@task
def render_template(threadComments, submission):
    #render the objects into a html file
    #does not return anything

现在,如果我在 (get_cmets(url) | render_template()).apply_asnc() 这样的链中调用它们,python 将抛出 TypeError: render_template() takes exactly 2 arguments (0 given)

我可以看到结果没有展开并应用于参数。如果我只调用 get_cmets,我可以这样做:

result = get_comments(url)
arg1, arg2 = result

得到两个结果。

【问题讨论】:

标签: python celery


【解决方案1】:

这里有两个错误。

首先,您不必致电get_comments()render_template()。相反,您应该使用.s() 任务方法。喜欢:

( get_comments.s(url) | render_template.s()).apply_async()

在您的情况下,您首先启动函数,然后尝试将函数结果连接到链中。

其次,实际上,您不会从第一个任务中返回“两个结果”。相反,您返回一个包含两个结果的元组,并且这个元组作为单个对象传递给第二个任务。

因此,您应该将第二个任务重写为

@task
def render_template(comments_and_submission):
   comments, submission = comments_and_submission

如果你解决了这些问题,它应该可以工作。

【讨论】:

  • 是的,这个固定的矿井也是如此。
  • 这是唯一的方法吗?有没有可能用star-arguement来实现它?
  • 这解决了这个问题,但我认为应该有一种方法来实现多个参数,因为任务可以在链中调用,也可以不调用。
猜你喜欢
  • 2014-11-03
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
相关资源
最近更新 更多