Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

urllib3 how to find code and message of Http error

I am catching http errors using python, but I want to know the code of the error (e.g. 400, 403,..). Additionally I want to get the message of the error. However, I can't find those two attributes in the documentation. Can anyone help? Thank you.

    try:
        """some code here"""
    except urllib3.exceptions.HTTPError as error:
        """code based on error message and code"""
like image 958
Funder Avatar asked Sep 10 '25 10:09

Funder


2 Answers

Assuming that you mean the description of the HTTP response when you said "the message of the error", you can use responses from http.client as in the following example:

import urllib3
from http.client import responses

http = urllib3.PoolManager()
request = http.request('GET', 'http://google.com')

http_status = request.status
http_status_description = responses[http_status]

print(http_status)
print(http_status_description)

...which when executed will give you:

200
OK

on my example.

I hope it helps. Regards.

like image 70
Marco Gomez Avatar answered Sep 13 '25 01:09

Marco Gomez


The following sample code illustrates status code of the response and cause of the error:

import urllib3
try:
  url ='http://httpbin.org/get'
  http = urllib3.PoolManager()
  response=http.request('GET', url)
  print(response.status)
except urllib3.exceptions.HTTPError as e:
  print('Request failed:', e.reason)

like image 40
superbCoder Avatar answered Sep 13 '25 00:09

superbCoder