django rest framework图片上传测试,以及drf测试所踩的一些坑

django rest framework图片上传测试

models.py

# http://easy-thumbnails.readthedocs.io/
# easy-thumbnails==2.3.0
from easy_thumbnails.fields import ThumbnailerImageField
class Dish(models.Model):
    name = models.CharField(_(u'name'), max_length=100)
    photo = ThumbnailerImageField(upload_to=dish_directory_path, null=True, blank=True, verbose_name=_(u'photo'))

serializers.py

class ThumbnailImageField(serializers.ImageField):
    """
    从 easy_thumbnails.fields.ThumbnailerImageField 字段类型中解析出缩略图信息
    """

    def __init__(self, *args, **kwargs):
        self.size_alias = kwargs.pop('size_alias', 'large')
        kwargs['read_only'] = True
        super(ThumbnailImageField, self).__init__(*args, **kwargs)

    def to_representation(self, value):
        try:
            return value[self.size_alias].url
        except Exception:
            return None

class DishSerializer(serializers.ModelSerializer):
    thumb = ThumbnailImageField(source="photo", size_alias='medium')

    class Meta:
        model = Dish

tests.py

    #from rest_framework.test import APITestCase

    def create_dish(self):
        #此处图片路径为绝大路径,static目录和tests.py文件同级
        image_path = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'static/test/dish_image.jpg')
        image_fp = open(image_path, 'rb')

        self.dish_data['photo'] = image_fp
        #注意post()的format值为"multipart"而不是json
        response = self.client.post(url, self.dish_data,
                                    format='multipart')
        image_fp.close()
        return response

    def test_create_dish(self):
        resp = self.create_dish()
        self.assertEqual(resp.status_code, status.HTTP_201_CREATED)
        self.assertEqual(self.dish_data['name'], resp.data['name'])
        self.assertTrue(resp.data['photo'])
        self.assertTrue('http://testserver/' in resp.data['photo'])

drf的解析器默认配置是

'DEFAULT_PARSER_CLASSES': (
    'rest_framework.parsers.JSONParser',
    'rest_framework.parsers.FormParser',
    'rest_framework.parsers.MultiPartParser'
)

如果是文件上传可能还要添加:
‘rest_framework.parsers.FileUploadParser’

drf测试所踩的一些坑

使用测试客户端的get方法上,习惯性的对url进行查询字符串拼装
(eg: search_url = “%s?name=%s” % (url, query)),
然后在调用时老是在self.client.get(search_url)里面抛出编码错误,各种转码,各种蛋疼,然后去看drf的get源码发现,完全不用拼装url,像post一样直接传递参数就可以了,如self.client.get(search_url,data={‘name’: query}),get函数内部已经实现转码。这件事告诉我们要多看源码,不要想当然啊

你可能感兴趣的:(django)