成功执行一个函数后运行另一个任务使用Celery

时间:2017-06-21 07:34:35

标签: python django celery django-celery

我是celery模块的新手,我想在成功执行特定功能后执行一项任务。

我在django app中做了以下更改:

更改settings.py

import djcelery
djcelery.setup_loader()
BROKER_URL = 'amqp://rahul:amvarish@127.0.0.1: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响应独立于celery任务执行?

1 个答案:

答案 0 :(得分:3)

您可以使用.apply_async调用您的任务以使调用异步,从而生成以下执行图:

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

根据上述内容,您应该在代码中调用add方法,如下所示:

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")