2017-06-21 136 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") 
相关问题