diff --git a/PythonLibs/CachedService.py b/PythonLibs/CachedService.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b4cf57792f43d9fa3362727d1d902d8a34acf6 --- /dev/null +++ b/PythonLibs/CachedService.py @@ -0,0 +1,29 @@ +import abc +from abc import ABC +from datetime import datetime +from typing import Dict + + +class CachedService(ABC): + def __init__(self, fetchThresholdInSeconds: int): + self._fetchThresholdInSeconds = fetchThresholdInSeconds + self._lastFetchTimestamp = 0 + self._data = None + + def get_data(self) -> Dict: + if self.__is_data_obsolete(): + self._data = self._fetch_data() + return self._data + + def __is_data_obsolete(self) -> bool: + now = datetime.now().timestamp() + if (now - self._lastFetchTimestamp) > self._fetchThresholdInSeconds: + self._lastFetchTimestamp = now + return True + + self._lastFetchTimestamp = now + return False + + @abc.abstractmethod + def _fetch_data(self) -> Dict: + pass diff --git a/PythonLibs/__init__.py b/PythonLibs/__init__.py index 2557fdf63502a976cfcdeeb34089aef223e9c058..45e31a966228a1bbc98da9e881630f168e5886e0 100644 --- a/PythonLibs/__init__.py +++ b/PythonLibs/__init__.py @@ -1,2 +1,3 @@ from PythonLibs.DefaultLogger import DefaultLogger from PythonLibs.MailHandler import MailHandler +from PythonLibs.CachedService import CachedService