30 lines
760 B
Python
30 lines
760 B
Python
import time
|
|
|
|
class Cache(dict):
|
|
|
|
def __init__(self, ttl=10):
|
|
self._ttl = ttl
|
|
self._added = {}
|
|
|
|
def get(self, key):
|
|
now = time.time()
|
|
for key, value in list(self._added.items()):
|
|
if value < now:
|
|
del self._added[key]
|
|
del self[key]
|
|
return dict.get(self, key)
|
|
|
|
def set(self, key, value, ttl=None):
|
|
ttl = ttl or self._ttl
|
|
self._added[key] = time.time() + ttl
|
|
dict.__setitem__(self, key, value)
|
|
|
|
def delete(self, key):
|
|
if key in self._added:
|
|
del self._added[key]
|
|
del self[key]
|
|
|
|
def clear(self, prefix):
|
|
for key in list(self):
|
|
if key.startswith(prefix):
|
|
self.delete(key)
|