使用Python请求模块获取HTTP响应头

har*_*lle 1 python http-headers python-requests

我在Python中使用'requests'模块来查询RESTful API端点.有时,端点返回HTTP错误500.我意识到我可以使用requests.status_code获取状态代码但是当我收到错误500时,我想看到HTTP"响应文本"(我不确定它叫什么,以下例子).到目前为止,我已经能够使用response.headers获取一些头文件.但是,我正在寻找的信息仍然不存在.

使用"curl -vvv",我可以看到我之后的HTTP响应(为清楚起见省略了一些输出):

< HTTP/1.1 200 OK <---------------------this is what I'm after)
* Server nginx/1.4.1 is not blacklisted
< Server: nginx/1.4.1
< Date: Wed, 05 Feb 2014 16:13:25 GMT
< Content-Type: application/octet-stream
< Connection: close
< Set-Cookie: webapp.session.id="mYzk5NTc0MDZkYjcxZjU4NmM=|1391616805|f83c47a363194c1ae18e"; expires=Fri, 07 Mar 2014 16:13:25 GMT; Path=/
< Content-Disposition: attachment; filename = "download_2014161325.pdf"
< Cache-Control: public
Run Code Online (Sandbox Code Playgroud)

再次,这是从卷曲.现在,当我使用Python的请求模块并询问标题时,这就是我得到的:

CaseInsensitiveDict(
 {
  'date': 'Tue, 04 Feb 2014 21:56:45 GMT',
  'set-cookie': 'webapp.session.id="xODgzNThlODkzZ2U0ZTg=|1391551005|a11ca2ad11195351f636fef"; expires=Thu, 06 Mar 2014 21:56:45 GMT; Path=/, 
  'connection': 'close',
  'content-type': 'application/json',
  'server': 'nginx/1.4.1'
 }
)
Run Code Online (Sandbox Code Playgroud)

请注意,curl响应包括"HTTP/1.1 200 OK",但requests.headers没有.几乎响应头中的其他所有内容都存在.requests.status_code给了我200.在这个例子中,我所追求的只是"OK".在其他情况下,我们的nginx服务器返回更详细的消息,如"HTTP/1.1 500搜索不可用"或"HTTP/1.1 500坏参数"等.我想得到这个文本.有没有办法或者我可以用Popen和卷曲来破解什么?Requests.content和requests.text没有帮助.

Mar*_*ers 6

您正在寻找Response.reason属性:

>>> import requests
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
>>> r.reason
'OK'
>>> r = requests.get('http://httpbin.org/status/500')
>>> r.reason
'INTERNAL SERVER ERROR'
Run Code Online (Sandbox Code Playgroud)

  • 缺少这方面的文件; 我添加了一个[pull request](https://github.com/kennethreitz/requests/pull/1904)来解决这个问题. (4认同)
  • 文档现已更新. (3认同)