bharatverse11 commited on
Commit
c2a9907
·
verified ·
1 Parent(s): 5b7c1e6

Create cache_manager.py

Browse files
Files changed (1) hide show
  1. cache_manager.py +59 -0
cache_manager.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from collections import OrderedDict
3
+
4
+ class CacheManager:
5
+ """
6
+ A simple LRU (Least Recently Used) Cache with Time-to-Live (TTL) support.
7
+ """
8
+ def __init__(self, capacity: int = 100, ttl_seconds: int = 3600):
9
+ """
10
+ Initialize the cache.
11
+ :param capacity: Maximum number of items to store.
12
+ :param ttl_seconds: Time in seconds before an item expires.
13
+ """
14
+ self.cache = OrderedDict()
15
+ self.capacity = capacity
16
+ self.ttl_seconds = ttl_seconds
17
+ print(f"🚀 CacheManager initialized with capacity={capacity} and TTL={ttl_seconds}s")
18
+
19
+ def get(self, key: str):
20
+ """
21
+ Retrieve an item from the cache.
22
+ :param key: The key to lookup.
23
+ :return: The cached value if found and valid, else None.
24
+ """
25
+ if key in self.cache:
26
+ result, timestamp = self.cache[key]
27
+ # Check if expired
28
+ if time.time() - timestamp < self.ttl_seconds:
29
+ # Move to end to mark as recently used
30
+ self.cache.move_to_end(key)
31
+ print(f"⚡ Cache HIT for query: '{key}'")
32
+ return result
33
+ else:
34
+ # Remove expired item
35
+ print(f"⌛ Cache EXPIRED for query: '{key}'")
36
+ del self.cache[key]
37
+ return None
38
+
39
+ def set(self, key: str, value):
40
+ """
41
+ Add an item to the cache.
42
+ :param key: The key to store.
43
+ :param value: The value to store.
44
+ """
45
+ if key in self.cache:
46
+ self.cache.move_to_end(key)
47
+
48
+ self.cache[key] = (value, time.time())
49
+ print(f"💾 Cache SET for query: '{key}'")
50
+
51
+ # Enforce capacity
52
+ if len(self.cache) > self.capacity:
53
+ removed = self.cache.popitem(last=False) # Remove first (least recently used)
54
+ print(f"🗑️ Cache full. Removed old entry: '{removed[0]}'")
55
+
56
+ def clear(self):
57
+ """Clear the entire cache."""
58
+ self.cache.clear()
59
+ print("🧹 Cache cleared.")