Обработка ошибок request python

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

61.4k77 gold badges189 silver badges308 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

176k34 gold badges275 silver badges318 bronze badges

answered Jan 29, 2012 at 16:52

kindall's user avatar

kindallkindall

179k35 gold badges279 silver badges310 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

176k34 gold badges275 silver badges318 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

17.1k13 gold badges60 silver badges105 bronze badges

answered Sep 6, 2017 at 9:57

kravietz's user avatar

kravietzkravietz

10.7k2 gold badges36 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,6141 gold badge17 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,7405 gold badges29 silver badges45 bronze badges

Часто в Python используется модуль requests для отправки HTTP-запросов. При работе с этим модулем могут возникать различные ошибки, например, проблемы с подключением.

Часто в Python используется модуль requests для отправки HTTP-запросов. При работе с этим модулем могут возникать различные ошибки, например, проблемы с подключением. В таких случаях обычно используется конструкция try/except для обработки исключений.

Пример использования try/except с модулем requests

Рассмотрим пример кода, где используется модуль requests для отправки GET-запроса на некоторый URL:

import requests

url = "https://www.example.com"

try:
    response = requests.get(url)
except requests.ConnectionError as e:
    print(e)

В данном случае, если при выполнении запроса произойдет ошибка подключения, Python сгенерирует исключение requests.ConnectionError, которое будет перехвачено в блоке except и вывод на печать.

Улучшение структуры кода

Структура кода в примере выше является корректной, но ее можно улучшить для более полного и удобного обработывания ошибок.

В модуле requests, помимо requests.ConnectionError, существуют и другие виды исключений, которые могут быть полезными для отлавливания ошибок. Например, requests.Timeout для ошибок связанных с тайм-аутом и requests.RequestException для отлавливания любых ошибок, которые могут возникнуть при выполнении запроса.

Пример улучшенного кода:

import requests

url = "https://www.example.com"

try:
    response = requests.get(url)
except requests.ConnectionError as e:
    print("Ошибка подключения:", e)
except requests.Timeout as e:
    print("Ошибка тайм-аута:", e)
except requests.RequestException as e:
    print("Ошибка запроса:", e)

Такая структура кода позволяет отлавливать и обрабатывать различные типы исключений, связанные с отправкой HTTP-запросов, что делает код более надежным и удобным для отладки.

При работе с веб-запросами немаловажным аспектом является правильная обработка ошибок и исключений. В процессе взаимодействия с веб-сервером может произойти множество различных ошибок, начиная от проблем соединения и заканчивая серверными ошибками.

Что такое HTTPError и как его обработать

HTTPError — это исключение, которое может быть вызвано библиотекой Requests, если сервер возвращает неудачный HTTP-ответ (например, 404 или 500).

Для того чтобы проверить ответ на наличие ошибок и, при необходимости, вызвать исключение, используется метод raise_for_status():

import requests

response = requests.get('https://www.example.com/')

try:
    response.raise_for_status()
except requests.HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')

Если сервер вернет статус-код ошибки, raise_for_status() вызовет исключение HTTPError. В приведенном выше коде это исключение перехватывается и обрабатывается.

Обработка других исключений в Requests

Помимо HTTPError, Requests может вызвать и другие исключения в зависимости от проблемы:

  • ConnectionError: Это исключение вызывается в случае проблем с соединением. Это может произойти, если, например, нет сетевого соединения или сервер недоступен.
  • Timeout: Если запрос к серверу не был выполнен в установленное время, будет вызвано это исключение. Время ожидания можно установить с помощью аргумента timeout при отправке запроса.
  • TooManyRedirects: Если запрос перенаправляется слишком много раз (больше установленного лимита), происходит это исключение.

Пример обработки различных исключений:

import requests

url = 'https://www.example.com/'

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()

except requests.Timeout:
    print(f"Timeout occurred for URL {url}")

except requests.ConnectionError:
    print(f"Connection error occurred for URL {url}")

except requests.TooManyRedirects:
    print(f"Too many redirects for URL {url}")

except requests.RequestException as error:
    print(f"An error occurred while fetching {url}: {error}")

Заключение

Правильная обработка ошибок и исключений позволяет создать устойчивое и надежное приложение, которое способно адекватно реагировать на различные проблемы во время выполнения веб-запросов. Библиотека Requests предоставляет простой и эффективный механизм для обработки самых распространенных исключений в процессе взаимодействия с веб-серверами.

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."""

Понравилась статья? Поделить с друзьями:
  • Обращение к авторитету логическая ошибка
  • Обратно пошел сильный дождь ошибка
  • Обработка ошибок spring mvc
  • Обратная ошибка хиндсайта
  • Обращение гуманно ошибки исправлены друзья образованы история безнравственна