python 请求

标签 python json python-requests html-post

我正在为 RESTful API POST-verb 编写测试,它将多部分表单数据发送到服务器。 我想对数据进行 json 编码。正确的方法是什么? 下面是 3 个测试,其中前 2 个通过,第三个(我需要的场景)失败。任何帮助将不胜感激。

import requests
import json

print "test 1, files+data/nojson"
requests.post('http://localhost:8080', files={'spot[photo]': open('test.jpg', 'rb')}, data={'spot': 'spot_description'})

print "test 2, only data/json"
requests.post('http://localhost:8080',data=json.dumps({'spot': 'spot_description'}))

print "test 3, only files+data/json"
requests.post('http://localhost:8080', files={'spot[photo]': open('test.jpg',
'rb')}, data=json.dumps({'spot': 'spot_description'}))

代码输出:

$ /cygdrive/c/Python27/python.exe -B test.py
test 1, files+data/nojson
test 2, only data/json
test 3, only files+data/json
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    'rb')}, data=json.dumps({'spot': 'spot_description'}))
  File "C:\Python27\lib\site-packages\requests\api.py", line 98, in post
    return request('post', url, data=data, **kwargs)
  File "C:\Python27\lib\site-packages\requests\safe_mode.py", line 39, in wrapped
    return function(method, url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 51, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 241, in request
    r.send(prefetch=prefetch)
  File "C:\Python27\lib\site-packages\requests\models.py", line 532, in send
    (body, content_type) = self._encode_files(self.files)
  File "C:\Python27\lib\site-packages\requests\models.py", line 358, in _encode_files
    fields = to_key_val_list(self.data)
  File "C:\Python27\lib\site-packages\requests\utils.py", line 157, in to_key_val_list
    raise ValueError('cannot encode objects that are not 2-tuples')
ValueError: cannot encode objects that are not 2-tuples

最佳答案

该错误是因为您的 data 参数是一个字符串。

models.py::send()中:

    # Multi-part file uploads.
    if self.files:
        (body, content_type) = self._encode_files(self.files)

models.py::_encode_files()中:

    fields = to_key_val_list(self.data)
    files = to_key_val_list(files)

utils.py::to_key_val_list()中:

if isinstance(value, (str, bytes, bool, int)):
    raise ValueError('cannot encode objects that are not 2-tuples')

这是在 self.data 通话中遇到的问题。您正在传递字典的字符串表示形式,但它需要字典本身,如下所示:

requests.post('http://localhost:8080',
              files={'spot[photo]': open('test.jpg', 'rb')},
              data={'spot': 'spot_description'})

因此,如果向文件参数分配了任何内容,则数据参数不能是 str、bytes、bool 或 int 类型。您可以按照源代码进行操作:https://github.com/kennethreitz/requests/blob/master/requests/models.py#L531

关于 python 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13731189/

相关文章:

javascript - 如何将从网络摄像头捕获的图像保存到文件夹

python - 可以在 2 个单独的进程之间共享内存中的数据吗?

json - 在艾考。如何在对话框中的自定义小部件内获取搜索查询参数?

php - 如何像数组对象一样访问 PHP 中的 JSON 元素?

python - 有没有办法发送 "refresh"请求?

python - 分配给 slice 有什么意义?

python - 从 JSON 中删除 JSON 对象?

json - 如何使用 Flask 发送和接收大型 numpy 数组(几个 GB)

python - 无法从我的本地 PC 和 AWS EC2 实例从 Twitter Web 获取相同的请求结果

python - 我是否需要使用 random.seed() 和 random.uniform() 来确保我得到不同的序列