pythonpython-3.xdjangohttp

Using the http.HTTPStatus class in Python to return the meaning of a HTTP status code


I'm trying to write a block of code to return the meaning (description) of an HTTP status code using the http.HTTPStatus Python class. I read the docs, but it seems I can only do the reverse. Is there way I can do this?

try:
    if resp.status != 200:
        message = 

Solution

  • This isn't in the HTTPStatus docs because the behavior you are looking for is inherited from Enum. From the documentation, in python, enum:

    uses call syntax to return members by value

    In your example, this can be used like:

    import http
    
    print( http.HTTPStatus(404).name )
    

    to get:

    'NOT_FOUND'