首页 > 解决方案 > JpegImageFile 类型的对象不是 JSON 可序列化的

问题描述

我正在尝试在我的网络应用程序中使用 celery,但我不知道具体如何。我在任务中取出图像更新,他不断抱怨序列化程序

任务.py

from celery import shared_task
@shared_task
def update_image(image, width, heigth):
    output_size = (width, heigth)
    image.thumbnail(output_size)
    image.save()

模型.py:

def save(self):
    img = Image.open(self.image.path)
    task = update_image.delay(img, self.width, self.heigth)

视图.py:

 def put(self, request, pk):
        saved_content = get_object_or_404(Content.objects.all(), pk=pk)
        data = request.data.get('content')
        serializer = ContentSerializer(
            instance=saved_content, data=data, partial=True)
        if serializer.is_valid(raise_exception=True):
            content_saved = serializer.save()
        return Response({
            "success": "Picture '{}' updated successfully".format(content_saved.id)
        })

错误:

Object of type JpegImageFile is not JSON serializable

Request Method: PUT

标签: djangocelery

解决方案


您可以通过这种方式传递 Image 对象,传递图像的路径并在任务内部打开它。

task = update_image.delay(self.image.path, self.width, self.heigth)

任务:

def update_image(path, width, height):
    image = Image.open(path)
    ...

推荐阅读