PR Review Lab · Add Retries to the Payment Client

30:00left of 30:00

Add Retries to the Payment Client

Charges sometimes fail on a flaky network, and checkout shows an error. This retries the charge with exponential backoff and moves the API key and retry count into config.py.

Mpayments/client.py1 of 3

Files Changed

payments/

tests/

payments/client.py

Python · Click a line number to comment · Tap a line to comment
@@ -1,20 +1,28 @@
import logging
Removed: import os
Added: import time
import requests
Added: from payments.config import API_KEY, MAX_RETRIES
Added:
log = logging.getLogger(__name__)
BASE_URL = "https://api.payments.example.com/v1"
class PaymentClient:
def __init__(self, http=None):
self.http = http or requests.Session()
Removed: self.http.headers["Authorization"] = f"Bearer {os.environ['PAYMENTS_API_KEY']}"
Added: self.http.headers["Authorization"] = f"Bearer {API_KEY}"
def charge(self, amount_cents, card_token):
body = {"amount": amount_cents, "currency": "usd", "source": card_token}
Removed: resp = self.http.post(f"{BASE_URL}/charges", json=body, timeout=10)
Added: for attempt in range(MAX_RETRIES):
Added: try:
Added: resp = self.http.post(f"{BASE_URL}/charges", json=body, timeout=10)
Added: break
Added: except Exception:
Added: log.warning("charge failed, retrying (attempt %d)", attempt)
Added: time.sleep(2 ** attempt)
resp.raise_for_status()
return resp.json()