Get HTTP Error code from requests.exceptions.HTTPError

PythonHttpExceptionPython Requests

Python Problem Overview


I am catching exceptions like this,

def get_url_fp(image_url, request_kwargs=None):
    response = requests.get(some_url, **request_kwargs)
    response.raise_for_status()
    return response.raw


try:
   a = "http://example.com"
   fp = get_url_fp(a)

except HTTPError as e:
    # Need to check its an 404, 503, 500, 403 etc.

Python Solutions


Solution 1 - Python

The HTTPError carries the Response object with it:

def get_url_fp(image_url, request_kwargs=None):
    response = requests.get(some_url, **request_kwargs)
    response.raise_for_status()
    return response.raw


try:
    a = "http://example.com"
    fp = get_url_fp(a)

except HTTPError as e:
    # Need to check its an 404, 503, 500, 403 etc.
    status_code = e.response.status_code

Solution 2 - Python

This is my code to get errors codes in HTTP

def tomcat_status(ip,port,url):
    try:
    # you can give your own url is
       r = urllib2.urlopen('http://'+ip+':'+port+'/'+url)
       return r.getcode()
     except urllib2.HTTPError as e:
       return e.code
    except urllib2.URLError as f:
       return 1
print tomcat_status(ip,tomcat_port,ping_url)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShiplu MokaddimView Question on Stackoverflow
Solution 1 - PythonLukasaView Answer on Stackoverflow
Solution 2 - PythonRajView Answer on Stackoverflow