-
Notifications
You must be signed in to change notification settings - Fork 0
/
persistent_cache.py
executable file
·46 lines (39 loc) · 1.24 KB
/
persistent_cache.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
41
42
43
44
45
46
import time
import os
import pickle
class PersistentCache:
def __init__(self, cache_file):
self.cache_file = cache_file
self.cache = self.load_cache()
def load_cache(self):
if os.path.exists(self.cache_file):
with open(self.cache_file, 'rb') as file:
try:
return pickle.load(file)
except (pickle.PickleError, EOFError):
pass
return {}
def save_cache(self):
with open(self.cache_file, 'wb') as file:
pickle.dump(self.cache, file)
def get(self, key, default=None):
if key in self.cache:
value, expiry = self.cache[key]
if expiry < time.time():
self.delete(key)
return default
return value
return default
def set(self, key, value, expiry_seconds=300):
expiry = None
if expiry_seconds is not None:
expiry = time.time() + expiry_seconds
self.cache[key] = (value, expiry)
self.save_cache()
def delete(self, key):
if key in self.cache:
del self.cache[key]
self.save_cache()
def clear(self):
self.cache.clear()
self.save_cache()