【问题标题】:Django rest frame work - File upload fails in test but working everywhere elseDjango 休息框架工作 - 文件上传在测试中失败,但在其他任何地方都可以工作
【发布时间】:2015-02-05 03:23:29
【问题描述】:

我正在尝试使用 django 1.7、DRF 2.4.3 和 Pillow 2.6.1 测试图像上传字段。

文件上传在管理员和我使用 curl 测试时正常工作

curl -X POST -S -H 'Accept: application/json' -F 'my_image=@hm.jpg;type=image/jpg' http://localhost:8000/api/randomresource/

当我在APITestCase 中进行类似测试时

temp_file = open('hm.jpg',"r")
response = self.client.post('randomresource', {"my_image":temp_file}, format='multipart')
self.assertEqual(response.status_code,status.HTTP_201_CREATED)

我明白了

{'my_image': [u'Upload a valid image. The file you uploaded was either not an image or a corrupted image.']}

感谢任何帮助。 谢谢。

【问题讨论】:

  • 您是否尝试过使用rb 标志而不是r?
  • 工作!发表一个答案,我会接受的。

标签: django unit-testing django-rest-framework


【解决方案1】:

@mariodev 昨天在 cmets 中回答了这个问题:

您是否尝试过使用 rb 标志而不是 r?

这是因为否则您将使用编码上传文件。对于文本文件和其他非二进制文件,这应该不是问题,但对于图像文件you need to open it as a binary file 等情况。

temp_file = open('hm.jpg',"rb")

当 Django REST Framework 使用 Pillow 检查图像是否有效时,如果编码错误,它将引发异常。这就是您收到错误的原因,因为 Django REST Framework 上传了文件,但无法验证它是图像。使用 curl 时编码是正确的,因为 curl 将其作为二进制文件上传并为您处理。

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 2017-09-12
    • 2012-08-21
    • 2017-04-22
    • 2018-04-02
    • 2016-10-07
    • 1970-01-01
    • 2021-11-14
    • 2012-05-07
    相关资源
    最近更新 更多