Skip to content
Snippets Groups Projects
Commit f02b46d6 authored by Robert Goldmann's avatar Robert Goldmann
Browse files

BaseUtils: added MultiCacheKeyService.py

parent 29c46f0e
No related branches found
No related tags found
No related merge requests found
import abc
from abc import ABC
from dataclasses import dataclass
from datetime import datetime
from typing import Dict
@dataclass
class CacheEntry:
key: str
lastFetchTimestamp: float
settings: Dict
cachedData: Dict
class MultiCacheKeyService(ABC):
def __init__(self, fetchThresholdInSeconds: int):
self._fetchThresholdInSeconds = fetchThresholdInSeconds
self._cache = {}
def get_data(self, cacheKey: str, settings: Dict) -> Dict:
if cacheKey not in self._cache:
self._cache[cacheKey] = CacheEntry(cacheKey, datetime.now().timestamp(), settings, {})
cacheEntry = self._cache[cacheKey]
if self.__is_data_obsolete(cacheEntry):
cacheEntry.cachedData = self._fetch_data(cacheEntry.settings)
return cacheEntry.cachedData
def __is_data_obsolete(self, cacheEntry: CacheEntry) -> bool:
now = datetime.now().timestamp()
if (now - cacheEntry.lastFetchTimestamp) > self._fetchThresholdInSeconds:
cacheEntry.lastFetchTimestamp = now
return True
return False
@abc.abstractmethod
def _fetch_data(self, settings: Dict) -> Dict:
pass
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment