Added retries to improve reliability

This commit is contained in:
Roger Gonzalez 2024-03-02 08:24:01 -03:00
parent 386a4a701f
commit 99aa104657
Signed by: rogs
GPG Key ID: C7ECE9C6C36EC2E6

View File

@ -17,6 +17,7 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import time
from datetime import datetime, timedelta
from time import sleep
from typing import List, Optional
@ -119,21 +120,24 @@ class UTEClient:
except KeyError:
raise TariffException("Tariff type not standard. Explicit definition required.")
def _make_request(self, method: str, url: str, data: Optional[dict] = None) -> requests.Response:
def _make_request(
self, method: str, url: str, data: Optional[dict] = None, retries: int = 5, delay: float = 2
) -> requests.Response:
"""
Make a HTTP request.
Make a HTTP request with retries.
Args:
method (str): The HTTP method to use. Accepted methods are ``GET``, ``POST``.
url (str): The URL to use for the request.
authorization (str): Authorization token
data (dict): The data to send in the body of the request.
retries (int): The number of times to retry the request.
delay (float): The delay in seconds between retries.
Returns:
requests.Response: The response object.
Raises:
Exception: If the method is not supported.
Exception: If the method is not supported or all retries fail.
"""
headers = {
"X-Client-Type": "Android",
@ -148,7 +152,17 @@ class UTEClient:
except AttributeError:
pass
return getattr(requests, method.lower(), self._method_not_supported)(url, headers=headers, json=data)
for attempt in range(retries):
try:
response = getattr(requests, method.lower(), self._method_not_supported)(url, headers=headers, json=data)
response.raise_for_status()
return response
except (requests.RequestException, Exception) as e:
if attempt == retries - 1:
raise e
time.sleep(delay)
raise Exception("All retries failed.")
def _method_not_supported(self, *args, **kwargs):
raise UnsupportedMethodException("HTTP method not supported")