django rest api test上传文件/图片

时间:2014-08-22 14:03:33

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

我实现了一个在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

1 个答案:

答案 0 :(得分:2)

好的,所以我遇到了完全相同的问题。这就是它对我有用的方式:

    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')

希望这会有所帮助:)