簡體   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