2014-05-26 11:41:59 +00:00
|
|
|
import time
|
|
|
|
|
|
|
|
class Cache(dict):
|
|
|
|
|
2016-01-05 15:12:25 +00:00
|
|
|
def __init__(self, ttl=10):
|
2014-05-26 11:41:59 +00:00
|
|
|
self._ttl = ttl
|
|
|
|
self._added = {}
|
|
|
|
|
|
|
|
def get(self, key):
|
2016-02-15 14:13:40 +00:00
|
|
|
now = time.time()
|
|
|
|
for key, value in self._added.items():
|
|
|
|
if value < now:
|
2014-05-26 11:41:59 +00:00
|
|
|
del self._added[key]
|
|
|
|
del self[key]
|
2016-02-15 14:13:40 +00:00
|
|
|
return dict.get(self, key)
|
2014-05-26 11:41:59 +00:00
|
|
|
|
|
|
|
def set(self, key, value, ttl=None):
|
|
|
|
ttl = ttl or self._ttl
|
|
|
|
self._added[key] = time.time() + ttl
|
|
|
|
dict.__setitem__(self, key, value)
|
2014-05-27 18:10:55 +00:00
|
|
|
|
|
|
|
def delete(self, key):
|
2016-01-05 14:06:42 +00:00
|
|
|
if key in self._added:
|
2014-05-27 18:10:55 +00:00
|
|
|
del self._added[key]
|
|
|
|
del self[key]
|
2016-01-17 11:02:17 +00:00
|
|
|
|
|
|
|
def clear(self, prefix):
|
|
|
|
for key in list(self):
|
|
|
|
if key.startswith(prefix):
|
|
|
|
self.delete(key)
|