Commit 2aae2ecb authored by alphyr's avatar alphyr
Browse files

Retry to connect to the API in case of failure

parent 729cfcb7
......@@ -6,6 +6,7 @@ import stat
import json
import requests
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from requests.exceptions import HTTPError
......@@ -27,7 +28,8 @@ class Re2oAPIClient:
def __init__(self, hostname, username, password, token_file=None,
use_tls=True, log_level=logging.CRITICAL+10):
use_tls=True, log_level=logging.CRITICAL+10, max_retries=0,
"""Creates an API client.
......@@ -43,6 +45,10 @@ class Re2oAPIClient:
(recommended for production). The default is `True`.
log_level: Control the logging level to use. The default is
`logging.CRITICAL+10`. So nothing is logged.
max_retries: The maximum number of retries if the client cannot
connect to the API. The default is 0.
wait_time: The time to wait between two API tests. It is ignored if
`max_retries` is 0. The default value is 10 seconds.
requests.exceptions.ConnectionError: Unable to resolve the
......@@ -76,6 +82,9 @@ class Re2oAPIClient:
self.hostname = hostname
self._username = username
self._password = password
self._check_api(max_retries, wait_time)
# Try to fetch token from token file else get a new one from the
# server
......@@ -83,6 +92,23 @@ class Re2oAPIClient:
except exceptions.APIClientGenericError:
def _check_api(self, max_retries, wait_time):
"""Checks if the API is responding to our requests"""
api_root = self.get_url_for("")
self.log.debug(f'Trying to connect to "{api_root}"')
for i in range(max_retries + 1):
r = requests.get(api_root)
except Exception as e:
self.log.warning(f"[{i}/{max_retries}] Unable to get an answer from {api_root}: {e}")
if i == max_retries:
raise e
def need_renew_token(self):
"""The token needs to be renewed.
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment