我正在 Python 中使用“请求”模块来查询 RESTful API 端点。有时,端点会返回 HTTP 错误 500。我意识到我可以使用 requests.status_code 获取状态代码,但是当我收到错误 500 时,我想查看 HTTP“响应文本”(我不确定它叫什么) ,示例如下)。到目前为止,我已经能够使用response.headers 获取一些 header 。但是,我要查找的信息仍然不存在。
使用“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
同样,这是来自curl。现在,当我使用 Python 的请求模块并请求 header 时,这就是我得到的全部:
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'
}
)
请注意,curl 响应包含“HTTP/1.1 200 OK”,但 requests.headers 不包含。响应 header 中的几乎所有其他内容都在那里。 requests.status_code 给我的是 200。在这个例子中,我所追求的只是“OK”。在其他场景中,我们的 nginx 服务器会返回更详细的消息,例如“HTTP/1.1 500 搜索不可用”或“HTTP/1.1 500 错误参数”等。我想获取此文本。有没有办法或者我可以用 Popen 和curl 来破解一些东西? requests.content 和 requests.text 没有帮助。
最佳答案
您正在寻找Response.reason
attribute :
>>> 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'
关于python - 使用Python请求模块获取HTTP响应头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583195/