【问题标题】:django rest api test to upload file/imagedjango rest api 测试上传文件/图像
【发布时间】:2014-10-16 10:01:41
【问题描述】:

我在 Django Rest 中实现了一个具有 ImageField 的简单模型。 它适用于 Django Rest 的 Browsable API。

但是,当我尝试编写测试用例来发布 JSON 时,它会引发错误 UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

您可以在下面查看测试代码。基本上,我打开测试图像并将其作为 JSON 参数传递 我不确定为什么它不能编码。

    test_image_filename = os.path.join('/vagrant/', 'test_images', 'test_image1.jpg')
    with open(test_image_filename) as image_file:
        data = {
                "location": "123, 123",
                "location_name": "location1",
                "date": datetime.datetime.now().__str__(),
                "max_attendee": 10,
                "description": "test",
                "image": image_file,
                "tags": []
            }
        response = self.client.post('/events/', data)
        print response

【问题讨论】:

  • 我认为应该是文件内容,而不是打开的文件对象

标签: json django file-upload django-rest-framework


【解决方案1】:

好的,所以我遇到了完全相同的问题。这对我来说是这样的:

    image_path = os.path.join('/vagrant/', 'test_image1.jpg')
    with open(image_path) as logo:
        encoded_logo = base64.b64encode(logo.read())
        data = {'name': 'Domus de magnum orexis, resuscitabo candidatus!', 
                'logo': encoded_logo,
                'about': 'The small planet revolutionary travels the phenomenon.'
            }
        response = self.client.post(url, data=json.dumps(data, ensure_ascii=False), content_type='application/json')

希望这会有所帮助:)

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多