diff --git a/re2oapi/client.py b/re2oapi/client.py index b67c1d8..6438017 100644 --- a/re2oapi/client.py +++ b/re2oapi/client.py @@ -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, + wait_time=10): """Creates an API client. Args: @@ -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. Raises: 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 try: @@ -83,6 +92,23 @@ class Re2oAPIClient: except exceptions.APIClientGenericError: self._force_renew_token() + 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): + try: + r = requests.get(api_root) + r.raise_for_status() + return + 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 + else: + time.sleep(wait_time) + @property def need_renew_token(self): """The token needs to be renewed.