【发布时间】:2014-02-05 16:43:09
【问题描述】:
我在 Python 中使用“请求”模块来查询 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
再次,这是来自 curl。现在,当我使用 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'
}
)
请注意 curl 响应包含“HTTP/1.1 200 OK”,但 requests.headers 不包含。响应标头中的几乎所有其他内容都在那里。 requests.status_code 给了我 200。在这个例子中,我所追求的只是“OK”。在其他情况下,我们的 nginx 服务器返回更详细的消息,例如“HTTP/1.1 500 搜索不可用”或“HTTP/1.1 500 参数错误”等。我想获取此文本。有没有办法或者我可以用 Popen 和 curl 破解一些东西? Requests.content 和 requests.text 没有帮助。
【问题讨论】:
标签: python http-headers python-requests