简体   繁体   中英

Celery EncodeError(TypeError('Object of type Response is not JSON serializable'))

I am using Celery - Redis - Django rest framework together. The error happens when I try to pass the serializer to the delay of celery within the Django rest framework.

Here is the viewset

class TestSet(viewsets.ModelViewSet):

    queryset = Test.objects.all()
    serializer_class = ImageSerializer

    def create(self, request, *args, **kwargs):
         serializer = TestSerializer(data=request.data)

         if serializer.is_valid():

            image_uploaded= "static_path"
            
            json_data = base64.b64encode(np.array(image_uploaded)).decode('ascii')
            result = test_call.delay({'image': json_data})
            result = test_call.delay(serializer)

            data = {"task": result.task_id}

            return Response(data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@shared_task(name="values")
def test_call(decoded_image):
    return decoded_image

The error I get is

EncodeError(TypeError('Object of type Response is not JSON serializable'))

Update: Even when I do this, I still get an error

result = test_call.delay({"task": 1})

@shared_task(name="values")
def test_call(decoded_image):
    return {"task": 2}

This isn't going to answer your question, but I can't leave a comment (low reputation).

It seems that you are trying to JSON Serialize something that obviously isn't JSON serializable. Based on the name, it is some kind of image data. You could try a different workflow that should be JSON Serializable, example:

One Example:

  1. first save the image somewhere that is accessible later and add the location in the serializer (S3 bucket and then a link to the image)
  2. In your celery task, fetch the image data based on that location

Second Example:

  1. convert the image data into something JSON serializable like a Base64 image string

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