-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmemorycache.py
40 lines (31 loc) · 1.09 KB
/
memorycache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import time, logging
class Cache():
def __init__(self, expires = 600):
logging.debug("Enabling memory cache, expires %s" % expires)
self.expires = expires
self.cache = {}
def keys(self):
return list(self.cache.keys())
def __len__(self):
return len(self.cache)
def __contains__(self, key):
return key in self.cache
def __getitem__(self, key):
now = int(time.time())
if key not in self.cache:
logging.debug("Cache MISS for " + str(key))
return None
if (now - self.cache[key]["saved"]) > self.expires:
# Cache value expired, remove and return None
logging.debug(str(key) + " expired, empty cache")
self.cache.pop(key, None)
return None
else:
logging.debug("Cache HIT for " + str(key))
return self.cache[key]["value"]
def __setitem__(self, key, value):
logging.debug("Saving %s in cache" % str(key))
self.cache[key] = {
"value" : value,
"saved" : int(time.time())
}