在我的django测试中,我想发送一个包含2个参数的HTTP Post Multipart:
def test_upload_request(self):
temp_file = tempfile.NamedTemporaryFile(delete=False).name
with open(temp_file) as f:
file_form = {
"file": f
}
my_json = json.dumps({
"list": {
"name": "test name",
"description": "test description"
}
})
response = self.client.post(reverse('api:upload'),
my_json,
content=file_form,
content_type="application/json")
os.remove(temp_file)
def upload(request):
print request.FILES['file']
print json.loads(request.body)
我的代码不起作用。有帮助吗? 如果有必要,我可以使用外部python库(我正在尝试请求) 谢谢
答案 0 :(得分:5)
使用application/json
内容类型,您无法上传文件。
请尝试以下操作:
视图:
def upload(request):
print request.FILES['file']
print json.loads(request.POST['json'])
return HttpResponse('OK')
试验:
def test_upload_request(self):
with tempfile.NamedTemporaryFile() as f:
my_json = json.dumps({
"list": {
"name": "test name",
"description": "test description"
}
})
form = {
"file": f,
"json": my_json,
}
response = self.client.post(reverse('api:upload'),
data=form)
self.assertEqual(response.status_code, 200)