Skip to content

Commit

Permalink
fix: make bank proxy retry on failure
Browse files Browse the repository at this point in the history
  • Loading branch information
AmooHashem committed Dec 18, 2024
1 parent 0c8a437 commit 0e34889
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions proxies/bank_service/bank.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,44 @@
from django.conf import settings
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from rest_framework import status
from rest_framework.response import Response

BANK_URL = settings.BANK_URL


# Configure retry strategy
def get_retry_session(retries=5, backoff_factor=0.3,
status_forcelist=(500, 502, 503, 504)):
"""
Create a requests session with retry capabilities.
Args:
retries (int): Number of total retries to allow.
backoff_factor (float): A backoff factor to apply between attempts.
status_forcelist (tuple): HTTP status codes to retry on.
Returns:
requests.Session: A configured session with retry capabilities
"""
retry_strategy = Retry(
total=retries,
status_forcelist=status_forcelist,
allowed_methods=["GET", "POST"], # Only retry these methods
backoff_factor=backoff_factor
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session = requests.Session()
session.mount("http://", adapter)
session.mount("https://", adapter)
return session


def _get(url, params):
try:
response = requests.get(
session = get_retry_session()
response = session.get(
url,
params=params,
timeout=10
Expand All @@ -17,14 +47,15 @@ def _get(url, params):
return response.json()
except requests.RequestException as e:
return Response(
{"error": f"Failed to process: {str(e)}"},
{"error": f"Failed to process GET request after retries: {str(e)}"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)


def _post(url, payload):
try:
response = requests.post(
session = get_retry_session()
response = session.post(
url,
json=payload,
timeout=10
Expand All @@ -33,7 +64,7 @@ def _post(url, payload):
return response.json()
except requests.RequestException as e:
return Response(
{"error": f"Failed to process: {str(e)}"},
{"error": f"Failed to process POST request after retries: {str(e)}"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)

Expand All @@ -43,9 +74,9 @@ def request_transfer(sender_id: str, receiver_id: str, funds: dict):
Send a transfer request to the transfer API endpoint.
Args:
sender_id (str): UUID of the receiver
sender_id (str): UUID of the sender
receiver_id (str): UUID of the receiver
currency_amounts (dict): Dictionary of currency names and amounts
funds (dict): Dictionary of currency names and amounts
Returns:
dict: Response from the transfer API or Response object with error
Expand Down

0 comments on commit 0e34889

Please sign in to comment.