MCPcopy Create free account
hub / github.com/NanmiCoder/MediaCrawler / ExpiringLocalCache

Class ExpiringLocalCache

cache/local_cache.py:34–128  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

32
33
34class ExpiringLocalCache(AbstractCache):
35
36 def __init__(self, cron_interval: int = 10):
37 """
38 Initialize local cache
39 :param cron_interval: Time interval for scheduled cache cleanup
40 :return:
41 """
42 self._cron_interval = cron_interval
43 self._cache_container: Dict[str, Tuple[Any, float]] = {}
44 self._cron_task: Optional[asyncio.Task] = None
45 # Start scheduled cleanup task
46 self._schedule_clear()
47
48 def __del__(self):
49 """
50 Destructor function, cleanup scheduled task
51 :return:
52 """
53 if self._cron_task is not None:
54 self._cron_task.cancel()
55
56 def get(self, key: str) -> Optional[Any]:
57 """
58 Get the value of a key from the cache
59 :param key:
60 :return:
61 """
62 value, expire_time = self._cache_container.get(key, (None, 0))
63 if value is None:
64 return None
65
66 # If the key has expired, delete it and return None
67 if expire_time < time.time():
68 del self._cache_container[key]
69 return None
70
71 return value
72
73 def set(self, key: str, value: Any, expire_time: int) -> None:
74 """
75 Set the value of a key in the cache
76 :param key:
77 :param value:
78 :param expire_time:
79 :return:
80 """
81 self._cache_container[key] = (value, time.time() + expire_time)
82
83 def keys(self, pattern: str) -> List[str]:
84 """
85 Get all keys matching the pattern
86 :param pattern: Matching pattern
87 :return:
88 """
89 if pattern == '*':
90 return list(self._cache_container.keys())
91

Callers 3

setUpMethod · 0.90
local_cache.pyFile · 0.85
create_cacheMethod · 0.85

Calls

no outgoing calls

Tested by 1

setUpMethod · 0.72