繁体   English   中英

如何返回完成的 celery 任务的结果并将数据存储在变量中?

[英]How do you return the result of a completed celery task and store the data in variables?

我有两个 flask 模块app.pytasks.py

我在tasks.py中设置了Celery来完成一个selenium webdriver请求(大约需要20秒)。 我的目标是简单地将该请求的结果返回给 app.py。

在另一个终端上运行 Celery 工作程序,我可以在控制台中看到 Celery 任务成功完成并打印了 selenium 请求中我需要的所有数据。 但是,现在我只想将任务结果返回给 app.py。

如何从 tasks.py 获取 celery 工作人员结果数据并将每个结果元素作为变量存储在 app.py 中?

应用程序.py:

我定义市场并调用任务 function 并请求索引结果:

import tasks

marketplace = 'cheddar_block_games'

# This is what I am trying to get back:
price_check = tasks.scope(marketplace[0])
image = tasks.scope(marketplace[1])

任务.py:

celery = Celery(broker='redis://127.0.0.1:6379')


 @celery.task()
 def scope(marketplace):
     web.get(f'https://magiceden.io/marketplace/{marketplace}')
     price_check = WebDriverWait(web,30).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[2]/div[2]/div[3]/div[2]/div[2]/div[3]/div[2]/div[4]/div/div[2]/div[1]/div[2]/div/div[2]/div/div[2]/div/span/div[2]/div/span[1]"))).text
     image = WebDriverWait(web,30).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[2]/div[2]/div[3]/div[2]/div[2]/div[3]/div[2]/div[4]/div/div[2]/div[1]/div[2]/div/div[1]/div/div/img")))

     return (price_check, image)
        

这个答案可能是相关的: https://stackoverflow.com/a/30760142/9347535

app.py 应该调用任务,例如使用 scope.delay 或 scope.apply_async。 然后,您可以使用 AsyncResult.get() 获取任务结果: https://docs.celeryq.dev/en/latest/userguide/tasks.html#result-backends

由于任务返回一个元组,您可以通过解包来存储每个变量: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences

结果将是这样的:

import tasks

marketplace = 'cheddar_block_games'

result = tasks.scope.delay(marketplace)
price_check, image = result.get()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM