Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP status code to status message

I'm looking for a way, in Python, to get the HTTP message from the status code. Is there a way that is better than building the dictionary yourself?

Something like:

>>> print http.codemap[404]
'Not found'
like image 630
Guy Markman Avatar asked Mar 12 '17 10:03

Guy Markman


People also ask

How can I get status code from HTTP status?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

What is HTTP status message?

When a browser requests a service from a web server, an error might occur, and the server might return an error code like "404 Not Found". It is common to name these errors HTML error messages. But these messages are something called HTTP status messages.

What does HTTP status message 204 refer to?

The HTTP 204 No Content success status response code indicates that a request has succeeded, but that the client doesn't need to navigate away from its current page. This might be used, for example, when implementing "save and continue editing" functionality for a wiki site.

What is a 422 error?

The HyperText Transfer Protocol (HTTP) 422 Unprocessable Entity response status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions.


3 Answers

In Python 2.7, the httplib module has what you need:

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

Constants are also available:

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

Update

@shao.lo added a useful comment bellow. The http.client module can be used:

# For Python 3 use
import http.client
http.client.responses[http.client.NOT_FOUND]
like image 99
abcdn Avatar answered Oct 24 '22 23:10

abcdn


Python 3:

You could use HTTPStatus(<error-code>).phrase to obtain the description for a given code value. E.g. like this:

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

Would give for example:

In func my_open got HTTP 415 Unsupported Media Type

Which answers the question. However a much more direct solution can be obtained from HTTPError.reason:

try:
    response = opener.open(url, data)
except HTTPError as e:
    print(f'In func my_open got HTTP {e.code} {e.reason}')
like image 38
hi2meuk Avatar answered Oct 24 '22 22:10

hi2meuk


This problem solved in Python 3.5 onward. Now Python http library has built-in module called HTTPStatus. You can easily get the http status details such as status code, description, etc. These are the example code for HTTPStatus.

like image 26
Kushan Gunasekera Avatar answered Oct 24 '22 21:10

Kushan Gunasekera