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

标签 python http-headers python-requests

我正在 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/

相关文章:

html - 我将网站发送到 Linux 服务器后,有些图片未显示

python - 使用自定义身份验证修改请求参数

python - 如何使用 python 请求将 tar.gz 和 jar 文件作为 GitHub Assets 上传?

python - 无法验证这些要求的哈希值,因为我们没有办法对版本控制存储库进行哈希处理

python - 如何将一串数字转换回二进制十六进制(\x 值)类型?

c# - 在 C# 中具有授权的 HTTPS 客户端

python - 如何使用 Flask 服务器的请求模块进行 POST?

python - 我如何在 Django 1.9 中排除 Django 数据库

python - 如何在 Windows 上安装 IMDbPY?

reactjs - 在react-native中发送请求 header /授权 axios.post