在DRF中测试ImageField

时间:2018-04-22 08:08:53

标签: python django django-rest-framework django-imagekit

我在models.py中使用Django Imagekit:

from imagekit.models import ProcessedImageField    
class AltroUser(models.Model):
        first_name = models.CharField(_('first name'), max_length=30)
        image = ProcessedImageField(upload_to='media/path',
                                    default='user_default.jpg',
                                    processors=[ResizeToFill(640, 640)],
                                    format='JPEG',
                                    options={'quality': 60})

serializers.py:

class UserRegistrationSerializer(Serializer):
    first_name = serializers.CharField()
    image = serializers.ImageField()

我正在尝试测试图像区域。我尝试了以下方法:

def get_test_image():
    try:
        image = DjangoFile(open(os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg'),
                                mode='rb'))
        return image
    except (OSError, IOError) as e:
        return None


def get_test_image1():
    file = io.BytesIO()
    image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0))
    image.save(file, 'png')
    file.name = 'test.png'
    file.seek(0)
    return SimpleUploadedFile('abc.jpg', file.read())


def get_test_image2():
    path = os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg')
    file = File(open(path, 'r+b'))
    return SimpleUploadedFile('abc.jpg', file.read())

我试过调用上面三种方法来设置图像键的值但是没有一种方法有效。 对于get_test_image(),我收到回复“提交的文件为空。”

对于get_test_image1()get_test_image2(),我之前在数据图片字段"The submitted file is empty."中收到了一个例外'_io.BytesIO' object has no attribute 'encoding'

我不明白我错过了什么。请帮忙。

2 个答案:

答案 0 :(得分:0)

以下是我用来生成测试图片的方法,这对我来说很好用:

from StringIO import StringIO
from PIL import Image
from django.core.files import File

def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
    file_obj = StringIO()
    image = Image.new("RGBA", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)

答案 1 :(得分:0)

Pillow==8.3.1 中,使用 StringIO() 给了我这个错误:

TypeError: string argument expected, got 'bytes'.

我改用了 BytesIO(),它的作用就像一个魅力

from io import BytesIO
def get_image_file(
    self, name="test.png", ext="png", size=(50, 50), color=(256, 0, 0)
):
    file_obj = BytesIO()
    image = Image.new("RGBA", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)