E
E
Error 5022016-05-14 15:33:02
Python
Error 502, 2016-05-14 15:33:02

Error Handling in Python - Sending a HTTPS Retry Request. How beautiful to implement?

I wrote a program in Python, one of the functions of which is to send an HTTPS request using the httplib2 library and receive a response. However, I ran into a problem: if the waiting time exceeded the specified interval, an error occurs. I decided to use an error handler and make sure that a request is sent again when a timeout occurs. And what if the error falls out again and again? Then I applied the recursion method and in case of an error the same function is called with the same parameter, but already inside it. Actually here is the resulting code:

def request(param):
  headers = {}
  url_get = 'https://example.com/?input='+str(param)
  https = httplib2.Http('.cache', timeout=10)
  try:
    resp, content = https.request(url_get, 'GET', headers=headers)
  except httplib2.ServerNotFoundError:
    print('Сервер недоступен, повторное подключение')
    content = request(param)
  except ConnectionRefusedError:
    print('Соединение разорвано, повторное подключение')
    content = request(param)
  except httplib2.socket.timeout:
    print('Таймаут запроса, повторное подключение')
    content = request(param)
  except OSError:
    print('Нету подключения к сети, ожидание 60 секунд')
    time.sleep(60)
    content = request(param)
  return content

The question is: is this method correct? Are there alternative options?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
arctblake, 2016-05-14
@NullByte

Вместо рекурсии - цикл. Зачем рекурсия, если вы просто повторяете одно и то же? Вместо фиксированного таймаута - динамический. Чаще всего делают степени двойки. При превышении какого-то макс значения - либо сброс до нуля, либо просто отключение.

S
sim3x, 2016-05-14
@sim3x

Использовать scrapy
Использовать очереди

A
angru, 2016-05-17
@angru

посмотрите на retrying

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question