From 730ad55e1eb9016e626f3357f30e6688e1256afa Mon Sep 17 00:00:00 2001 From: Robert Goldmann <deadlocker@gmx.de> Date: Sat, 2 May 2020 11:21:32 +0200 Subject: [PATCH] added CachedService --- PythonLibs/CachedService.py | 29 +++++++++++++++++++++++++++++ PythonLibs/__init__.py | 1 + 2 files changed, 30 insertions(+) create mode 100644 PythonLibs/CachedService.py diff --git a/PythonLibs/CachedService.py b/PythonLibs/CachedService.py new file mode 100644 index 0000000..b8b4cf5 --- /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 2557fdf..45e31a9 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 -- GitLab