Gui*_*ent 5 python testing django post http
在我的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)
Run Code Online (Sandbox Code Playgroud)
我的代码不起作用.有帮助吗?如果有必要,我可以使用外部python lib(我正在尝试请求)谢谢
使用application/json内容类型,您无法上传文件.
试试以下:
视图:
def upload(request):
print request.FILES['file']
print json.loads(request.POST['json'])
return HttpResponse('OK')
Run Code Online (Sandbox Code Playgroud)
测试:
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)
Run Code Online (Sandbox Code Playgroud)