简体   繁体   中英

How to wait for results from a celery task in Django

I have a celery task which sends data to another service. I have added the celery task send_inventory_request into RequestSupplyStock class based view. when I make a post I should first get results from celery task and then continue and return a response. I would like to first wait for the result from celery task and then return response from the post method which is the proper way to achieve this.

@app.task
def send_inventory_request(payload,token):
    auth = {'authorization':token}
    HEADERS.update(auth)
    url = PROCUREMENT_SUPPLY_STOCK_REQUESTS_URL
    res = requests.post(url,json=payload,headers=HEADERS)
    inventory_request_data = res.json()
    x= logger.info('Supply Stock Request {0} + {1}'.format(payload,token))
    print(x)
    return inventory_request_data 

View

class RequestSupplyStock(generics.CreateAPIView):

      def post(self, request, format=None):
          ........

          send_inventory_request.delay(payload,get_token(request))

          .........
          return Response(status=status.HTTP_201_CREATED)

You can use celery wait , but it's not recommended

Waiting for tasks within a task may lead to deadlocks. Please read Avoid launching synchronous subtasks.

task = send_inventory_request.delay(payload,get_token(request))
result = task.wait(timeout=None, interval=0.5)

As others already mentioned in the comment, waiting for the result in synchronous manner defeats the purpose of using celery but if you still need to wait for the result then don't delay .

Just call the task like a normal method and it will run synchronously and return the result:

send_inventory_request(payload,get_token(request))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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