|
| 1 | +import json |
| 2 | +import logging |
| 3 | + |
| 4 | +import requests |
| 5 | +from django.conf import settings |
| 6 | +from django.http import HttpResponse |
| 7 | +from rest_framework import status |
| 8 | +from rest_framework.exceptions import APIException |
| 9 | + |
| 10 | +from middleware.utils import generate_jwt |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class CareClient: |
| 16 | + auth_header_type = "Gateway_Bearer" |
| 17 | + |
| 18 | + def __init__(self): |
| 19 | + self.base_url = settings.CARE_API |
| 20 | + self.timeout = settings.CARE_API_TIMEOUT |
| 21 | + |
| 22 | + def _get_url(self, endpoint): |
| 23 | + return f"{self.base_url}{endpoint}" |
| 24 | + |
| 25 | + def _get_headers(self): |
| 26 | + return { |
| 27 | + "Authorization": f"{self.auth_header_type} {generate_jwt()}", |
| 28 | + "X-Gateway-Id": settings.GATEWAY_DEVICE_ID, |
| 29 | + "Accept": "application/json", |
| 30 | + } |
| 31 | + |
| 32 | + def _make_request( |
| 33 | + self, method: str, url: str, as_http_response=False, **request_kwargs |
| 34 | + ) -> HttpResponse | dict: |
| 35 | + """ |
| 36 | + Execute the HTTP request and validate the response. |
| 37 | +
|
| 38 | + Args: |
| 39 | + method: HTTP method (GET, POST, etc.) |
| 40 | + url: Full URL to request |
| 41 | + as_http_response: If True, return HttpResponse object instead of JSON |
| 42 | + **request_kwargs: Additional arguments to pass to requests method |
| 43 | +
|
| 44 | + Returns: |
| 45 | + HttpResponse or dict depending on as_http_response flag |
| 46 | +
|
| 47 | + Raises: |
| 48 | + APIException: For all request failures with appropriate error messages |
| 49 | + """ |
| 50 | + try: |
| 51 | + response = requests.request( |
| 52 | + method, url, timeout=self.timeout, **request_kwargs |
| 53 | + ) |
| 54 | + |
| 55 | + # Handle response based on format requested |
| 56 | + if as_http_response: |
| 57 | + return HttpResponse( |
| 58 | + response.content, |
| 59 | + content_type=response.headers.get( |
| 60 | + "content-type", "application/json" |
| 61 | + ), |
| 62 | + status=response.status_code, |
| 63 | + ) |
| 64 | + |
| 65 | + if response.status_code >= status.HTTP_400_BAD_REQUEST: |
| 66 | + raise APIException(response.text, response.status_code) |
| 67 | + |
| 68 | + return response.json() |
| 69 | + |
| 70 | + except requests.Timeout as e: |
| 71 | + raise APIException( |
| 72 | + {"error": f"Request timed out after {self.timeout} seconds"}, |
| 73 | + status.HTTP_504_GATEWAY_TIMEOUT, |
| 74 | + ) from e |
| 75 | + except ( |
| 76 | + requests.ConnectionError, |
| 77 | + requests.exceptions.SSLError, |
| 78 | + requests.exceptions.TooManyRedirects, |
| 79 | + requests.RequestException, |
| 80 | + ) as e: |
| 81 | + logger.error(f"Gateway connection error: {str(e)}") |
| 82 | + raise APIException( |
| 83 | + {"error": "Failed to connect to gateway device"}, |
| 84 | + status.HTTP_503_SERVICE_UNAVAILABLE, |
| 85 | + ) from e |
| 86 | + except json.decoder.JSONDecodeError as e: |
| 87 | + raise APIException( |
| 88 | + {"error": "Invalid JSON response from gateway device"}, |
| 89 | + status.HTTP_502_BAD_GATEWAY, |
| 90 | + ) from e |
| 91 | + except Exception as e: |
| 92 | + logger.error(f"Unexpected error during gateway request: {str(e)}") |
| 93 | + raise APIException( |
| 94 | + {"error": "An unexpected error occurred during gateway request"}, |
| 95 | + status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 96 | + ) from e |
| 97 | + |
| 98 | + def get(self, endpoint, data=None, as_http_response=False): |
| 99 | + url = self._get_url(endpoint) |
| 100 | + return self._make_request( |
| 101 | + "GET", |
| 102 | + url, |
| 103 | + as_http_response=as_http_response, |
| 104 | + params=data, |
| 105 | + headers=self._get_headers(), |
| 106 | + ) |
| 107 | + |
| 108 | + def post(self, endpoint, data=None, as_http_response=False): |
| 109 | + url = self._get_url(endpoint) |
| 110 | + return self._make_request( |
| 111 | + "POST", |
| 112 | + url, |
| 113 | + as_http_response=as_http_response, |
| 114 | + json=data, |
| 115 | + headers=self._get_headers(), |
| 116 | + ) |
0 commit comments