Convert HTTP response code to text message with Python standard package
Question:
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.
Answers:
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
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'
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.
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
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'