From d36b5d906c78aaaebf988b4b41cf562819d29530 Mon Sep 17 00:00:00 2001 From: Prafful Sharma <115104695+DraKen0009@users.noreply.github.com> Date: Thu, 19 Sep 2024 19:58:21 +0530 Subject: [PATCH] added timeout to middleware requests (#2434) * added timeout to middleware requests * updated the reference for timeout value in function --------- Co-authored-by: Vignesh Hari <14056798+vigneshhari@users.noreply.github.com> --- care/utils/assetintegration/base.py | 11 +++++++++++ config/settings/base.py | 6 ++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/care/utils/assetintegration/base.py b/care/utils/assetintegration/base.py index d43690b39d..3a430dcad0 100644 --- a/care/utils/assetintegration/base.py +++ b/care/utils/assetintegration/base.py @@ -16,6 +16,7 @@ def __init__(self, meta): self.host = self.meta["local_ip_address"] self.middleware_hostname = self.meta["middleware_hostname"] self.insecure_connection = self.meta.get("insecure_connection", False) + self.timeout = settings.MIDDLEWARE_REQUEST_TIMEOUT def handle_action(self, action): pass @@ -37,12 +38,17 @@ def api_post(self, url, data=None): url, json=data, headers=self.get_headers(), + timeout=self.timeout, ) try: response = req.json() if req.status_code >= 400: raise APIException(response, req.status_code) return response + + except requests.Timeout: + raise APIException({"error": "Request Timeout"}, 504) + except json.decoder.JSONDecodeError: raise APIException({"error": "Invalid Response"}, req.status_code) @@ -51,11 +57,16 @@ def api_get(self, url, data=None): url, params=data, headers=self.get_headers(), + timeout=self.timeout, ) try: if req.status_code >= 400: raise APIException(req.text, req.status_code) response = req.json() return response + + except requests.Timeout: + raise APIException({"error": "Request Timeout"}, 504) + except json.decoder.JSONDecodeError: raise APIException({"error": "Invalid Response"}, req.status_code) diff --git a/config/settings/base.py b/config/settings/base.py index e12c643dec..7c934f830b 100644 --- a/config/settings/base.py +++ b/config/settings/base.py @@ -6,10 +6,10 @@ import json from datetime import datetime, timedelta from pathlib import Path -from django.utils.translation import gettext_lazy as _ import environ from authlib.jose import JsonWebKey +from django.utils.translation import gettext_lazy as _ from healthy_django.healthcheck.celery_queue_length import ( DjangoCeleryQueueLengthHealthCheck, ) @@ -55,7 +55,6 @@ # https://docs.djangoproject.com/en/dev/ref/settings/#locale-paths LOCALE_PATHS = [str(BASE_DIR / "locale")] - LANGUAGES = [ ("en-us", _("English")), ("ml", _("Malayalam")), @@ -663,3 +662,6 @@ TASK_SUMMARIZE_DISTRICT_PATIENT = env.bool( "TASK_SUMMARIZE_DISTRICT_PATIENT", default=True ) + +# Timeout for middleware request (in seconds) +MIDDLEWARE_REQUEST_TIMEOUT = env.int("MIDDLEWARE_REQUEST_TIMEOUT", 20)