openmedialibrary/oml/cache.py

26 lines
633 B
Python
Raw Normal View History

2014-05-26 13:41:59 +02:00
import time
class Cache(dict):
2016-01-05 20:42:25 +05:30
def __init__(self, ttl=10):
2014-05-26 13:41:59 +02:00
self._ttl = ttl
self._added = {}
def get(self, key):
if key in self._added:
if self._added[key] < time.time():
del self._added[key]
del self[key]
return
return dict.__getitem__(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)
2014-05-27 20:10:55 +02:00
def delete(self, key):
2016-01-05 19:36:42 +05:30
if key in self._added:
2014-05-27 20:10:55 +02:00
del self._added[key]
del self[key]