Skip to content

Commit

Permalink
feat: add request helper class
Browse files Browse the repository at this point in the history
  • Loading branch information
alimghmi committed Oct 22, 2023
1 parent b023e09 commit 76c8432
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ URL="https://www.ice.com/public-web/cds-settlement-prices/icc/single-names"
LOG_LEVEL="INFO"
OUTPUT_TABLE=
INSERTER_MAX_RETRIES=2
REQUEST_MAX_RETRIES=3
REQUEST_BACKOFF_FACTOR=2
MSSQL_SERVER=
MSSQL_DATABASE=
MSSQL_USERNAME=
Expand Down
2 changes: 2 additions & 0 deletions config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
LOG_LEVEL = config("LOG_LEVEL", default="INFO")
OUTPUT_TABLE = config("OUTPUT_TABLE")
INSERTER_MAX_RETRIES = config("INSERTER_MAX_RETRIES", default=3, cast=int)
REQUEST_MAX_RETRIES = config("REQUEST_MAX_RETRIES", default=3, cast=int)
REQUEST_BACKOFF_FACTOR = config("REQUEST_BACKOFF_FACTOR", default=2, cast=int)
MSSQL_SERVER = config("MSSQL_SERVER")
MSSQL_DATABASE = config("MSSQL_DATABASE")
MSSQL_USERNAME = config("MSSQL_USERNAME")
Expand Down
1 change: 1 addition & 0 deletions utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .db_helper import create_inserter_objects
from .request_helper import Request
24 changes: 24 additions & 0 deletions utils/request_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import time

import requests

from config import logger


class Request:
def __init__(self, max_retries, backoff_factor) -> None:
self.max_retries = max_retries
self.backoff_factor = backoff_factor

def request(self, method: str, url: str, *args, **kwargs) -> requests.Request:
for i in range(self.max_retries):
try:
return requests.request(method=method, url=url, *args, **kwargs)
except requests.exceptions.RequestException as e:
logger.error(
f"{method.upper()} request failed. Attempt {i + 1} of {self.max_retries}. Error: {e}" # noqa: E501
)
if (i + 1) == self.max_retries:
raise

time.sleep(i**self.backoff_factor)

0 comments on commit 76c8432

Please sign in to comment.