2017-06-21 90 views
1

我是celery模塊的新手,我想要在成功執行特定函數後執行一個任務。成功執行一個函數後運行另一個任務使用芹菜

我已經做了我的Django應用程序的以下變化:

變化settings.py

import djcelery 
djcelery.setup_loader() 
BROKER_URL = 'amqp://rahul:[email protected]:5672//' 
CELERY_ACCEPT_CONTENT = ['json'] 
CELERY_TASK_SERIALIZER = 'json' 
CELERY_RESULT_SERIALIZER = 'json' 
CELERY_IMPORTS = ('projectmanagement.tasks',) 

創建tasks.py

from celery import task 
    @task() 
    def add(x, y): 
     print (x+y) 
     return x + y 

view.py

class Multiply(APIView): 
    def get(self,request): 
     x = request.GET['x'] 
     y = request.GET['y'] 
     try: 
      z= x*y 
      data = {'success':True,'msg':'x and y multiply','result':z} 
      return HttpResponse(json.dumps(data),content_type="application/json") 
     except Exception,e: 
      print str(e) 
      data = {'success':False,'msg':'Error in multiplying x and y'} 
      return HttpResponse(json.dumps(data),content_type="application/json") 

現在我希望我的芹菜任務在我的multiply方法成功執行後被調用。

我應該在我的視圖函數中調用我的任務,這樣我的API響應將獨立於芹菜任務執行?

+0

嘿@ piyush-s-wanare我想知道,我的回答有幫助嗎? –

回答

2

您可以致電與.apply_async你的任務進行呼叫異步的,這將導致以下執行圖:

       | 
           | 
          normal flow 
           | 
           |   async 
         my_task.apply_async -------> do my task_stuff 
           |   call 
           | 
          flow continues 
       without waiting on my_task execution 
           | 
           ... 

從上面提到的,在你的代碼,你應該打電話給你附加的方法派生如下:

from path.to.your.tasks import add 

class Multiply(APIView): 
    def get(self,request): 
     x = request.GET['x'] 
     y = request.GET['y'] 
     try: 
      z= x*y 
      add.apply_async(x, y) # will execute independently 
      data = {'success':True,'msg':'x and y multiply','result':z} 
      return HttpResponse(json.dumps(data),content_type="application/json") 
     except Exception,e: 
      print str(e) 
      data = {'success':False,'msg':'Error in multiplying x and y'} 
      return HttpResponse(json.dumps(data),content_type="application/json")