Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
Вместо рекурсии - цикл. Зачем рекурсия, если вы просто повторяете одно и то же? Вместо фиксированного таймаута - динамический. Чаще всего делают степени двойки. При превышении какого-то макс значения - либо сброс до нуля, либо просто отключение.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question