使用Python标准包将HTTP响应代码转换为文本消息

buh*_*htz 3 python http http-headers python-3.x

这个问题是关于HTTP 响应代码的。

在我的 python 应用程序中,我想向用户展示与此类代码相关的文本。例如404将是Not Found

我检查了 python 文档,但找不到为我提供代码文本/字符串的包。python 库中真的没有这样的东西吗?

解决方法是使用外部源。例如,来自 IANA 的官方 CSV 文件。

buh*_*htz 6

感谢@Ohad 的提示。对于Python3.x,我看到了两种不错的方法。

1 - 使用requests模块

>>> from requests import status_codes
>>> mycode = 404
>>> status_codes._codes[mycode][0]
'not_found'
Run Code Online (Sandbox Code Playgroud)

2 - 使用http.client模块

>>> from http.client import responses
>>> responses[404]
'Not Found'
Run Code Online (Sandbox Code Playgroud)