我正在尝试实现一个简单的Django视图,该视图接受文件附件和一些其他参数,并在远程API调用上代理该请求。请注意:代理不是我要问的重点:)这就是我实现视图的方式:def image_upload(request): token = request.POST['token'] image_file = request.FILES.values()[0] files = {'file': ('myupload.txt', image_file.read())} client_id = request.POST['client_id'] folder_id = request.POST['folder_id'] advert_id = request.POST['advert_id'] image_type = request.POST['image_type'] crop_image = request.POST['crop_image'] api_base_url = settings.API_BASE_URL file_post_data = {'client_id': client_id, 'folder_id': folder_id, 'advert_id': advert_id, 'image_type': image_type, 'crop_image': crop_image} auth_header = {'Authorization': 'Token ' + token} r = requests.post(api_base_url + 'assets/image/upload/', data = json.dumps(file_post_data), headers = auth_header, files = files) return r.json()问题是,当我测试该视图时(我使用Django Test Client进行此操作),在“ files = files”行上出现错误,提示“ ValueError:无法对非2元组的对象进行编码”。完整的跟踪日志是以下内容:======================================================================ERROR: test_image_upload (fbx.tests.FbxTest)----------------------------------------------------------------------Traceback (most recent call last): File "/home/andrea/Documents/src/fbxapp/onboard/fbx/tests.py", line 18, in test_image_upload 'image_type': 'A', 'crop_image': False, 'attachment': fp}) File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 449, in post response = super(Client, self).post(path, data=data, content_type=content_type, **extra) File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 262, in post return self.request(**r) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response response = callback(request, *callback_args, **callback_kwargs) File "/home/andrea/Documents/src/fbxapp/onboard/fbx/views.py", line 42, in image_upload files = files) File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 88, in post return request('post', url, data=data, **kwargs) File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 44, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 324, in request prep = req.prepare() File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 225, in prepare p.prepare_body(self.data, self.files) File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 385, in prepare_body (body, content_type) = self._encode_files(files, data) File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 99, in _encode_files fields = to_key_val_list(data or {}) File "/usr/local/lib/python2.7/dist-packages/requests/utils.py", line 136, in to_key_val_list raise ValueError('cannot encode objects that are not 2-tuples')ValueError: cannot encode objects that are not 2-tuples我也尝试过使用它来读取文件的快速测试:files = {'file':('myupload.txt',open('/ tmp / mytmp.txt','rb'))}但这不起作用。您对如何解决此问题有任何想法吗?谢谢! 最佳答案 您不能同时发布JSON数据和multipart/form-data,这实际上就是您要在此处执行的操作。 json.dumps返回一个字符串,因此您发送的字符串看起来像'{"client_id": 1, "folder_id": 2, "advert_id": 3, "image_type": "jpeg", "crop_image": true}'然后通过通过multipart/form-data参数发送一些内容来告诉请求您要将其与files请求结合使用。那是不可能的,可能会引发更好的例外。将文件读入内存后,将文件添加到JSON数据中,然后使用适当的Content-Type标头将其发送,或者将整个内容作为multipart/form-data请求发送,而无需使用json.dumps并将简单地创建的字典传递给。使用一个或另一个,但不能同时使用。顺便说一句,您说您的异常来自仅包含data的行,但不是仅该行会导致异常。恰好在该行结束的函数引发了异常。您的例外情况也由此引起的事实仅仅是巧合。这是Python中的疣,可能在Python 3.4中已修复。您应该升级,因为3.4将会很棒,并且Django的较新版本支持Python3.x。关于python - 无法使用Python请求库发布POST文件附件和数据参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19658703/ 10-16 22:47