状态消息的 HTTP 状态代码

HTTP status code to status message

我正在 Python 中寻找一种从状态代码获取 HTTP 消息的方法。有没有比自己建字典更好的方法?

类似于:

>>> print http.codemap[404]
'Not found'

在Python 2.7中,httplib模块有你需要的:

>>> import httplib
>>> httplib.responses[400]
'Bad Request

常量也可用:

httplib.responses[httplib.NOT_FOUND]
httplib.responses[httplib.OK]

更新

@shao.lo added a useful comment bellow. The http.client 可以使用的模块:

# For Python 3 use
import http.client
http.client.responses[http.client.NOT_FOUND]

404 错误表示页面可能已被移动或离线。它不同于 400 错误,后者指示指向一个不存在的页面。

此问题已在 Python 3.5 及更高版本中解决。现在 Python http 库有一个名为 HTTPStatus. You can easily get the http status details such as status code, description, etc. These are the example code for HTTPStatus.

的内置模块

Python 3:

您可以使用 HTTPStatus(<error-code>).phrase 获取给定代码值的描述。例如。像这样:

try:
    response = opener.open(url, 
except HTTPError as e:
    print(f'In func my_open got HTTP {e.code} {HTTPStatus(e.code).phrase}')

例如:

In func my_open got HTTP 415 Unsupported Media Type

这回答了问题。但是,可以从 HTTPError.reason:

获得更直接的解决方案
try:
    response = opener.open(url, data)
except HTTPError as e:
    print(f'In func my_open got HTTP {e.code} {e.reason}')