1+ from cachetools import TTLCache , Cache
2+ from datetime import datetime
3+
4+ import cachetools
5+ import time
6+ import pickle
7+
8+ def hashkey (* args , ** kwargs ):
9+ new_args = []
10+ for i in range (0 , len (args )):
11+ new_args .append (str (args [i ]))
12+ args = tuple (new_args )
13+
14+ for k in kwargs :
15+ kwargs [k ] = str (kwargs [k ])
16+
17+ return (cachetools .keys .hashkey (* args , ** kwargs ))
18+
19+
20+ class TTLCacheStorage (TTLCache ):
21+ def __init__ (self , maxsize , ttl , storage = None , storage_sync_timer = 0 , timer = time .monotonic , getsizeof = None ):
22+ self .storage = storage
23+ self .storage_sync_timer = storage_sync_timer
24+
25+ now = datetime .timestamp (datetime .now ())
26+ self .storage_sync_timer_next = now
27+
28+ super ().__init__ (maxsize , ttl , timer , getsizeof )
29+
30+ if self .storage is not None :
31+ try :
32+ with open (self .storage , 'rb' ) as fh :
33+ self ._Cache__data = pickle .load (fh )
34+ print ("[TTLCacheStorage] Load" , self .storage )
35+ except :
36+ pass
37+
38+ def __getitem__ (self , key , cache_getitem = Cache .__getitem__ ):
39+ v = super ().__getitem__ (key , cache_getitem )
40+
41+ if self .storage is not None :
42+ now = datetime .timestamp (datetime .now ())
43+ if self .storage_sync_timer_next <= now :
44+ self .storage_sync_timer_next = now + self .storage_sync_timer
45+
46+ with open (self .storage , 'wb' ) as fh :
47+ pickle .dump (self ._Cache__data , fh )
48+ print ("[TTLCacheStorage] Sync" , self .storage )
49+
50+ return v
0 commit comments