From c3373ab0d97cb90acbfbb9d5982dcd57445aad2a Mon Sep 17 00:00:00 2001 From: Paul Schilling Date: Thu, 21 Sep 2023 16:02:53 +0200 Subject: [PATCH] [#1744] Monkey-patched requests to add default timeouts --- src/open_inwoner/cms/cases/views/status.py | 1 - src/open_inwoner/conf/base.py | 2 ++ src/open_inwoner/setup.py | 27 ++++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/open_inwoner/cms/cases/views/status.py b/src/open_inwoner/cms/cases/views/status.py index 1dfcbfadd4..0981836a85 100644 --- a/src/open_inwoner/cms/cases/views/status.py +++ b/src/open_inwoner/cms/cases/views/status.py @@ -12,7 +12,6 @@ from django.views.generic import FormView, TemplateView from django_htmx.http import HttpResponseClientRedirect -from glom import glom from mail_editor.helpers import find_template from view_breadcrumbs import BaseBreadcrumbMixin from zgw_consumers.api_models.constants import RolOmschrijving diff --git a/src/open_inwoner/conf/base.py b/src/open_inwoner/conf/base.py index 8a358b2c84..63029412c3 100644 --- a/src/open_inwoner/conf/base.py +++ b/src/open_inwoner/conf/base.py @@ -44,6 +44,8 @@ ("nl", _("Dutch")), ] +# Default (connection timeout, read timeout) for the requests library (in seconds) +DEFAULT_TIMEOUT_REQUESTS = (10, 60) TIME_ZONE = "Europe/Amsterdam" # note: this *may* affect the output of DRF datetimes diff --git a/src/open_inwoner/setup.py b/src/open_inwoner/setup.py index 2a257fa552..f08aa57438 100644 --- a/src/open_inwoner/setup.py +++ b/src/open_inwoner/setup.py @@ -9,9 +9,15 @@ do NOT import anything Django related here, as this file needs to be loaded before Django is initialized. """ +import logging import os +from django.conf import settings + from dotenv import load_dotenv +from requests import Session + +logger = logging.getLogger(__name__) def setup_env(): @@ -20,3 +26,24 @@ def setup_env(): load_dotenv(dotenv_path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "open_inwoner.conf.dev") + + monkeypatch_requests() + + +def monkeypatch_requests(): + """ + Add a default timeout for any requests calls. + """ + if hasattr(Session, "_original_request"): + logger.debug( + "Session is already patched OR has an ``_original_request`` attribute." + ) + return + + Session._original_request = Session.request + + def new_request(self, *args, **kwargs): + kwargs.setdefault("timeout", settings.DEFAULT_TIMEOUT_REQUESTS) + return self._original_request(*args, **kwargs) + + Session.request = new_request