6

在我的 django 测试中,我想发送一个包含 2 个参数的 HTTP Post Multipart:

  • 一个 JSON 字符串
  • 一份文件
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 库(我正在尝试requests)谢谢

4

1 回答 1

8

使用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)
于 2013-08-18T13:21:12.033 回答