Skip to content

Commit 6b833f3

Browse files
kikkomepEttoreM
authored andcommitted
feat(http): reconfigure existing HttpRequester singleton instead of recreating it
1 parent 22fecd1 commit 6b833f3

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

rocrate_validator/utils/http.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,18 @@ def initialize_cache(cls,
357357
:param no_cache: When ``True``, disable the HTTP cache entirely and
358358
use a plain ``requests.Session``. Incompatible with ``offline``.
359359
"""
360+
with cls._lock:
361+
instance = cls._instance
362+
if instance is None:
363+
return cls(cache_max_age=cache_max_age, cache_path=cache_path,
364+
offline=offline, no_cache=no_cache)
365+
# Re-apply the configuration without recreating the instance:
366+
# we keep the same singleton in place and only rebuild its underlying session,
367+
# rather than dropping and recreating the object (as ``reset`` does).
368+
instance._reconfigure(cache_max_age=cache_max_age, cache_path=cache_path,
369+
offline=offline, no_cache=no_cache)
370+
return instance
371+
360372
def _close_session(self) -> None:
361373
"""Close the current session and remove its cache file if it is temporary."""
362374
session = getattr(self, "session", None)
@@ -371,6 +383,30 @@ def _close_session(self) -> None:
371383
except Exception as e:
372384
logger.debug("Error cleaning up previous cache: %s", e)
373385

386+
def _reconfigure(self,
387+
cache_max_age: int = constants.DEFAULT_HTTP_CACHE_MAX_AGE,
388+
cache_path: Optional[str] = None,
389+
offline: bool = False,
390+
no_cache: bool = False) -> None:
391+
"""
392+
Rebuild the underlying session with new cache settings while preserving
393+
the singleton instance (and any attributes set on it, e.g. test patches).
394+
"""
395+
with self._lock:
396+
self._close_session()
397+
try:
398+
self.cache_max_age = int(cache_max_age)
399+
except ValueError:
400+
raise TypeError("cache_max_age must be an integer")
401+
self.cache_path_prefix = cache_path
402+
self.offline = bool(offline)
403+
self.no_cache = bool(no_cache)
404+
self.permanent_cache = cache_path is not None
405+
# ``__initialize_session__`` asserts the instance is not yet initialized.
406+
self._initialized = False
407+
self.__initialize_session__(cache_max_age, cache_path)
408+
self._initialized = True
409+
374410
@classmethod
375411
def reset(cls) -> None:
376412
"""

0 commit comments

Comments
 (0)