Python'请求'模块和编码?

时间:2013-10-28 07:54:47

标签: python python-requests

我正在使用请求模块执行简单的POST请求,并针对httpbin

对其进行测试
import requests

url      = 'http://httpbin.org/post'
params   = {'apikey':'666666'}
sample   = {'sample': open('test.bin', 'r')}

response = requests.post( url, files=sample, params=params, verify=False)
report_info = response.json()
print report_info

我遇到编码问题。它没有使用application/octet-stream,因此编码不正确。从标题中,我看到:

{
  u'origin': u'xxxx, xxxxxx', 
  u'files': {
               u'sample': u'data:None;base64,qANQR1DBw..........

因此,当我尝试使用data:None时,我会获得data:application/octet-stream而不是curl。文件大小和编码不正确。

如何强制或检查它是否正在使用application/octet-stream

1 个答案:

答案 0 :(得分:1)

取自http://www.python-requests.org/en/latest/user/quickstart/#custom-headers

的样本
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}

>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

您可能希望将headers更改为

headers = {'content-type': 'application/octet-stream'}
response = requests.post( url, files=sample, params=params, verify=False,
             headers = headers)