【发布时间】:2018-10-05 03:38:26
【问题描述】:
我正在尝试测试我的 Django REST API 以进行文件上传。
问题是我的服务器尝试验证文件,以便文件具有可识别的文件类型。目前只允许使用基于文本的文件类型,例如:docs、pdf、txt。
我尝试过使用临时文件,现在我只是尝试从磁盘读取文件然后放弃了。
每当我使用临时文件时,服务器都会响应:
{
"cover_letter": [
"The submitted data was not a file. Check the encoding type on the form."
],
"manuscript": [
"The submitted data was not a file. Check the encoding type on the form."
]
}
这是我的测试:
def test_user_can_submit_a_paper(self):
"""
Ensure that an user is able to upload a paper.
This test is not working.. yet
"""
tmp_file = open("__init__.py", "w")
data = {
"title": "paper",
"authors": "me",
"description": "ma detailed description",
"manuscript": base64.b64encode(tmp_file.read()).decode(),
"cover_letter": base64.b64encode(tmp_file.read()).decode()
}
tmp_file.close()
response = self.client.post(self.papers_submitted, data=urlencode(MultiValueDict(data)), content_type='application/x-www-form-urlencoded',
HTTP_AUTHORIZATION=self.authorization_header)
print(response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
del data["cover_letter"]
response = self.client.post(self.papers_submitted, data=urlencode(MultiValueDict(data)), content_type='application/x-www-form-urlencoded',
HTTP_AUTHORIZATION=self.authorization_header)
print(response.data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
我已经通过邮递员成功测试了这个端点,但我不知道如何在 Python 中进行。
【问题讨论】:
标签: django django-rest-framework