Django REST :: AssertionError:图片格式无效

时间:2017-01-19 15:12:35

标签: python django django-rest-framework

我有View这样:

class LogoView(APIView):
    permission_classes = [UserWriteSafeReadPermission]

    def get_object(self):
        return Config.objects.get(domain=self.request.domain)

    ...

    def put(self, request, pk=None, format=None, **kwargs):
        config = self.get_object()

        try:
            image = request.FILES['image']
            config.set_logo(image)
            return Response(status=status.HTTP_201_CREATED)
        except KeyError:
            return Response(status=status.HTTP_400_BAD_REQUEST, data={'detail': 'Expected image.'})

A model

def set_logo(self, image_data):
    ....
    try:
        image = Image.open(image_data) # <-- fails

unittest

def test_foo(self):
        self.authenticate(USER_PERMISSION_WRITE)

        from PIL import Image
        import tempfile

        image = Image.new('RGB', (100, 100))
        tmp_file = tempfile.NamedTemporaryFile(suffix='.png')
        image.save(tmp_file)

        response = self.client.put(self.api_reverse('my_url'), {'image': tmp_file}, format='multipart')

得到:

断言错误:图像格式无效

编辑:当我调试image = Image.open(image_data)时,我看到了:

(Pdb) image_data.file.read()
''

1 个答案:

答案 0 :(得分:0)

以下是我为测试目的创建图像的方法,我在SO中找到了这个解决方案,也许它可以帮到你。

from StringIO import StringIO
from PIL import Image

.....
def create_image_file(self):
    image_file = StringIO()
    image = Image.new('RGBA', size=(50, 50), color=(256, 0, 0))
    image.save(image_file, 'png')
    image_file.seek(0)
    return ContentFile(image_file.read(), 'test.png')