Request exception ошибка

ec == const.IETaskNotFound or # 36016 or # sc == 404 Task was not found
					# the following was found by xslidian, but i have never ecountered before
					ec == 31390):  # sc == 404 # {"error_code":31390,"error_msg":"Illegal File"} # r.url.find('http://bcscdn.baidu.com/bcs-cdn/wenxintishi') == 0
					result = ec
					# TODO: Move this out to cdl_cancel() ?
					#if ec == const.IETaskNotFound:
					#	pr(r.json())
					if dumpex:
						self.__dump_exception(None, url, pars, r, act)
				else:
					# gate for child classes to customize behaviors
					# the function should return ERequestFailed if it doesn't handle the case
					result = self.__handle_more_response_error(r, sc, ec, act, actargs)
					if result == const.ERequestFailed and dumpex:
						self.__dump_exception(None, url, pars, r, act)
		except (requests.exceptions.RequestException,
				socket.error,
				ReadTimeoutError) as ex:
			# If certificate check failed, no need to continue
			# but prompt the user for work-around and quit
			# why so kludge? because requests' SSLError doesn't set
			# the errno and strerror due to using **kwargs,
			# so we are forced to use string matching
			if isinstance(ex, requests.exceptions.SSLError) 
				and re.match(r'^[Errno 1].*error:14090086.*:certificate verify failed$', str(ex), re.I):
				# [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
				result = const.EFatal
				self.__dump_exception(ex, url, pars, r, act)
				perr("nn== Baidu's Certificate Verification Failure ==n"
				"We couldn't verify Baidu's SSL Certificate.n"
				"It's most likely that the system doesn't have "
				"the corresponding CA certificate installed.n"

Source code for requests.exceptions

"""
requests.exceptions
~~~~~~~~~~~~~~~~~~~

This module contains the set of Requests' exceptions.
"""
from urllib3.exceptions import HTTPError as BaseHTTPError

from .compat import JSONDecodeError as CompatJSONDecodeError


[docs]class RequestException(IOError): """There was an ambiguous exception that occurred while handling your request. """ def __init__(self, *args, **kwargs): """Initialize RequestException with `request` and `response` objects.""" response = kwargs.pop("response", None) self.response = response self.request = kwargs.pop("request", None) if response is not None and not self.request and hasattr(response, "request"): self.request = self.response.request super().__init__(*args, **kwargs)

class InvalidJSONError(RequestException): """A JSON error occurred."""

[docs]class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): """Couldn't decode the text into json""" def __init__(self, *args, **kwargs): """ Construct the JSONDecodeError instance first with all args. Then use it's args to construct the IOError so that the json specific args aren't used as IOError specific args and the error message from JSONDecodeError is preserved. """ CompatJSONDecodeError.__init__(self, *args) InvalidJSONError.__init__(self, *self.args, **kwargs)

[docs]class HTTPError(RequestException): """An HTTP error occurred."""

[docs]class ConnectionError(RequestException): """A Connection error occurred."""

class ProxyError(ConnectionError): """A proxy error occurred.""" class SSLError(ConnectionError): """An SSL error occurred."""

[docs]class Timeout(RequestException): """The request timed out. Catching this error will catch both :exc:`~requests.exceptions.ConnectTimeout` and :exc:`~requests.exceptions.ReadTimeout` errors. """

[docs]class ConnectTimeout(ConnectionError, Timeout): """The request timed out while trying to connect to the remote server. Requests that produced this error are safe to retry. """

[docs]class ReadTimeout(Timeout): """The server did not send any data in the allotted amount of time."""

[docs]class URLRequired(RequestException): """A valid URL is required to make a request."""

[docs]class TooManyRedirects(RequestException): """Too many redirects."""

class MissingSchema(RequestException, ValueError): """The URL scheme (e.g. http or https) is missing.""" class InvalidSchema(RequestException, ValueError): """The URL scheme provided is either invalid or unsupported.""" class InvalidURL(RequestException, ValueError): """The URL provided was somehow invalid.""" class InvalidHeader(RequestException, ValueError): """The header value provided was somehow invalid.""" class InvalidProxyURL(InvalidURL): """The proxy URL provided is invalid.""" class ChunkedEncodingError(RequestException): """The server declared chunked encoding but sent an invalid chunk.""" class ContentDecodingError(RequestException, BaseHTTPError): """Failed to decode response content.""" class StreamConsumedError(RequestException, TypeError): """The content for this response was already consumed.""" class RetryError(RequestException): """Custom retries logic failed""" class UnrewindableBodyError(RequestException): """Requests encountered an error when trying to rewind a body.""" # Warnings class RequestsWarning(Warning): """Base warning for Requests.""" class FileModeWarning(RequestsWarning, DeprecationWarning): """A file was opened in text mode, but Requests determined its binary length.""" class RequestsDependencyWarning(RequestsWarning): """An imported dependency doesn't match the expected version range."""

Python request module is a simple and elegant Python HTTP library. It provides methods for accessing Web resources via HTTP. In the following article, we will use the HTTP GET method in the Request module. This method requests data from the server and the Exception handling comes in handy when the response is not successful. Here, we will go through such situations. We will use Python’s try and except functionality to explore the exceptions that arise from the Requests module.

  • url: Returns the URL of the response
  • raise_for_status(): If an error occur, this method returns a HTTPError object
  • request: Returns the request object that requested this response
  • status_code: Returns a number that indicates the status (200 is OK, 404 is Not Found)
     

Successful Connection Request

The first thing to know is that the response code is 200 if the request is successful.

Python3

Output:

200

Exception Handling for HTTP Errors

Here, we tried the following URL sequence and then passed this variable to the Python requests module using raised_for_status(). If the try part is successful, we will get the response code 200, if the page that we requested doesn’t exist. This is an HTTP error, which was handled by the Request module’s exception HTTPError and you probably got the error 404.

Python3

import requests

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.HTTPError as errh:

    print("HTTP Error")

    print(errh.args[0])

print(r)

Output:

HTTP Error
404 Client Error: Not Found for url: https://www.amazon.com/nothing_here
<Response [404]>

General Exception Handling

You could also use a general exception from the Request module. That is requests.exceptions.RequestException.

Python3

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.RequestException as errex:

    print("Exception request")

Output:

Exception request 

Now, you may have noticed that there is an argument ‘timeout’ passed into the Request module. We could prescribe a time limit for the requested connection to respond. If this has not happened, we could catch that using the exception requests.exceptions.ReadTimeout. To demonstrate this let us find a website that responds successfully.

Python3

import requests

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.ReadTimeout as errrt:

    print("Time out")

print(r)

Output:

<Response [200]>

If we change timeout = 0.01, the same code would return, because the request could not possibly be that fast.

Time out
<Response [200]>

Exception Handling for Missing Schema

Another common error is that we might not specify HTTPS or HTTP in the URL. For example, We cause use requests.exceptions.MissingSchema to catch this exception.

Python3

url = "www.google.com"

try:

    r = requests.get(url, timeout=1)

    r.raise_for_status()

except requests.exceptions.MissingSchema as errmiss:

    print("Missing schema: include http or https")

except requests.exceptions.ReadTimeout as errrt:

    print("Time out")

Output:

Missing scheme: include http or https

Exception Handling for Connection Error

Let us say that there is a site that doesn’t exist. Here, the error will occur even when you can’t make a connection because of the lack of an internet connection

Python3

try:

  r = requests.get(url, timeout = 1, verify = True)

  r.raise_for_status()

except requests.exceptions.HTTPError as errh:

  print("HTTP Error")

  print(errh.args[0])

except requests.exceptions.ReadTimeout as errrt:

  print("Time out")

except requests.exceptions.ConnectionError as conerr:

  print("Connection error")

Output:

Connection error

Putting Everything Together

Here, We put together everything we tried so far the idea is that the exceptions are handled according to the specificity. 

For example, url =  “https://www.gle.com”,  When this code is run for this URL will produce an Exception request. Whereas, In the absence of connection requests.exceptions.ConnectionError will print the Connection Error, and when the connection is not made the general exception is handled by requests.exceptions.RequestException.

Python3

try:

    r = requests.get(url, timeout=1, verify=True)

    r.raise_for_status()

except requests.exceptions.HTTPError as errh:

    print("HTTP Error")

    print(errh.args[0])

except requests.exceptions.ReadTimeout as errrt:

    print("Time out")

except requests.exceptions.ConnectionError as conerr:

    print("Connection error")

except requests.exceptions.RequestException as errex:

    print("Exception request")

Output:

Note: The output may change according to requests.

 Time out

Last Updated :
23 Jan, 2023

Like Article

Save Article

How to handle exceptions with python library requests?
For example how to check is PC connected to internet?

When I try

try:
    requests.get('http://www.google.com')
except ConnectionError:
    # handle the exception

it gives me error name ConnectionError is not defined

Kevin Burke's user avatar

Kevin Burke

60.2k76 gold badges186 silver badges302 bronze badges

asked Jan 29, 2012 at 16:46

1

Assuming you did import requests, you want requests.ConnectionError. ConnectionError is an exception defined by requests. See the API documentation here.

Thus the code should be:

try:
   requests.get('http://www.google.com')
except requests.ConnectionError:
   # handle the exception

The original link to the Python v2 API documentation from the original answer no longer works.

tripleee's user avatar

tripleee

174k33 gold badges271 silver badges313 bronze badges

answered Jan 29, 2012 at 16:52

kindall's user avatar

kindallkindall

178k35 gold badges274 silver badges305 bronze badges

4

As per the documentation, I have added the below points:

  1. In the event of a network problem (refused connection e.g internet issue), Requests will raise a ConnectionError exception.

    try:
       requests.get('http://www.google.com')
    except requests.ConnectionError:
       # handle ConnectionError the exception
    
  2. In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.
    Response.raise_for_status() will raise an HTTPError if the HTTP request returned an unsuccessful status code.

    try:
       r = requests.get('http://www.google.com/nowhere')
       r.raise_for_status()
    except requests.exceptions.HTTPError as err:
       #handle the HTTPError request here
    
  3. In the event of times out of request, a Timeout exception is raised.

You can tell Requests to stop waiting for a response after a given number of seconds, with a timeout arg.

    requests.get('https://github.com/', timeout=0.001)
    # timeout is not a time limit on the entire response download; rather, 
    # an exception is raised if the server has not issued a response for
    # timeout seconds
  1. All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException. So a base handler can look like,

    try:
       r = requests.get(url)
    except requests.exceptions.RequestException as e:
       # handle all the errors here
    

The original link to the Python v2 documentation no longer works, and now points to the new documentation.

tripleee's user avatar

tripleee

174k33 gold badges271 silver badges313 bronze badges

answered Jul 28, 2019 at 9:47

abhishek kasana's user avatar

Actually, there are much more exceptions that requests.get() can generate than just ConnectionError. Here are some I’ve seen in production:

from requests import ReadTimeout, ConnectTimeout, HTTPError, Timeout, ConnectionError

try:
    r = requests.get(url, timeout=6.0)
except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
    continue

Falko's user avatar

Falko

16.9k13 gold badges59 silver badges104 bronze badges

answered Sep 6, 2017 at 9:57

kravietz's user avatar

kravietzkravietz

10.6k2 gold badges35 silver badges27 bronze badges

1

Include the requests module using import requests .

It is always good to implement exception handling. It does not only help to avoid unexpected exit of script but can also help to log errors and info notification. When using Python requests I prefer to catch exceptions like this:

try:
    res = requests.get(adress,timeout=30)
except requests.ConnectionError as e:
    print("OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.n")
    print(str(e))            
    continue
except requests.Timeout as e:
    print("OOPS!! Timeout Error")
    print(str(e))
    continue
except requests.RequestException as e:
    print("OOPS!! General Error")
    print(str(e))
    continue
except KeyboardInterrupt:
    print("Someone closed the program")

answered May 23, 2018 at 20:19

Tanmoy Datta's user avatar

Tanmoy DattaTanmoy Datta

1,5941 gold badge16 silver badges15 bronze badges

1

for clarity, that is

except requests.ConnectionError:

NOT

import requests.ConnectionError

You can also catch a general exception (although this isn’t recommended) with

except Exception:

answered Feb 22, 2015 at 10:50

StackG's user avatar

StackGStackG

2,7105 gold badges28 silver badges45 bronze badges

exception documentation

class RequestException(IOError): (source)

Known subclasses: requests.exceptions.ChunkedEncodingError, requests.exceptions.ConnectionError, requests.exceptions.ContentDecodingError, requests.exceptions.HTTPError, requests.exceptions.InvalidHeader, requests.exceptions.InvalidJSONError, requests.exceptions.InvalidSchema, requests.exceptions.InvalidURL, requests.exceptions.MissingSchema, requests.exceptions.RetryError, requests.exceptions.StreamConsumedError, requests.exceptions.Timeout, requests.exceptions.TooManyRedirects, requests.exceptions.UnrewindableBodyError, requests.exceptions.URLRequired

View In Hierarchy

There was an ambiguous exception that occurred while handling your
request.

Method __init__ Initialize RequestException with `request` and `response` objects.
Instance Variable request Undocumented
Instance Variable response Undocumented

def __init__(self, *args, **kwargs):

(source)

Initialize RequestException with `request` and `response` objects.

Понравилась статья? Поделить с друзьями:
  • Reptilicus ошибка при разборе ответа
  • Report json 1c ошибка
  • Replace toner cartridge brother ошибка
  • Replace image drum oki ошибка
  • Replace drum cart xerox 3330 ошибка