How to return the data from django signal?

Viewed 730

I am using Django-rest for developing the API. In my case, when the user posts the data, I have to process the posted data (It will take 2-3 min). I wrote the Django signal for preprocessing data. My signal.py file looks like this,

@receiver(post_save, sender=ExposureIndex)
def calculate_exposure(instance, created, *args, **kwargs):
    ear_table = instance.ear_index.name
    haz_dir = instance.hazard_index.file.path

    # calling celery task
    task = exposure_calculation.delay(ear_table,haz_dir)

    return task.id

And my celery calculation function is here,

@shared_task(bind=True)
def exposure_calculation(self, ear_table, haz_dir):
    progress_recorder = ProgressRecorder(self)

    CalculateExposure(ear_table, haz_dir)

    return 'Done'

My django-rest view function is looks like this,

class ExposureIndexViewSet(viewsets.ModelViewSet):
    queryset = ExposureIndex.objects.all()
    serializer_class = ExposureIndexSerializer
    permission_classes = [permissions.IsAuthenticated]

My question is when the user posts the data, I want to return the task.id instead of returning the actual response (I tried to return it from the Django signal but it is not returning in the actual API). Can anyone suggest to me how to return task.id instantly when the user posts the exposureIndexData?

2 Answers

instead of using signals u can simply send response through your view

def post(self,request):
  #create database manaully
  task=exposure_calculation.delay(ear_table,haz_dir)
  return Response({"message",task.id})

I think you should override the create method in views.py rather than creating the signal instance. Do something like this in views.py file

class ExposureIndexViewSet(viewsets.ModelViewSet):
    queryset = ExposureIndex.objects.all()
    serializer_class = ExposureIndexSerializer
    permission_classes = [permissions.IsAuthenticated]

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        instance = response.data
        ear_table = instance['ear_table']
        haz_dir = instance['haz_dir']

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        task = exposure_calculation.delay(ear_table,haz_dir)

        return Response({'task_id': task.id})
Related