buhtz
buhtz

Reputation: 12152

Convert HTTP response code to text message with Python standard package

This question is about the HTTP Response Codes.

In my python application I want to present the user the text related to such a code. e.g. 404 would be Not Found.

I checked the python docs but couldn't found a package which give me the text/string for the codes. Isn't there really nothing like this in the python libraries?

A workaround would be to use an external source. E.g. the official CSV file from the IANA.

Upvotes: 3

Views: 1814

Answers (2)

Nihal Sangeeth
Nihal Sangeeth

Reputation: 5515

You can use http standard library in Python3.

list(http.HTTPStatus) will give you the complete list.

You can get the name and value attributes:

for x in list(http.HTTPStatus):
    print(str(x.value) + ' : ' + x.name)

prints:

    100 : CONTINUE
    101 : SWITCHING_PROTOCOLS
    102 : PROCESSING
    200 : OK
    201 : CREATED

.....

    510 : NOT_EXTENDED
    511 : NETWORK_AUTHENTICATION_REQUIRED

Upvotes: 3

buhtz
buhtz

Reputation: 12152

Thanks to @Ohad for the hint. With Python3.x I see two nice ways.

1 - Using requests module

>>> from requests import status_codes
>>> mycode = 404
>>> status_codes._codes[mycode][0]
'not_found'

2 - Using http.client module

>>> from http.client import responses
>>> responses[404]
'Not Found'

Upvotes: 7

Related Questions