大家在使用requests的post 方法提交数据时, 经常使用的方法如下:
1. 提交python字典格式的数据
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
2. 提交Json格式数据
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))
或者
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
3. 提交文件
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> payload = {'some': 'data'}
>>> r = requests.post(url, files=files, json=payload)
这样操作看似没有问题, 也可以正常提交. 但是实际json参数并没有起作用, 在官网中有这样一句话, 如果大家不注意可能发现不了: Note, the json
parameter is ignored if either data
or files
is passed.(如果提交参数中使用data或files, 那么json参数将被忽略)
那么正确的操作是:
# files + dict参数提交方式
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> payload = {'some': 'data'}
>>> r = requests.post(url, files=files, data=payload)
print '---------------------------我是方法分割线---------------------------------'
# files + json参数提交方式
import json
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> payload = {'some': 'data'}
>>> r = requests.post(url, files=files, data=json.dumps(payload))
参考官方文档
http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file