openmedialibrary/oml/cache.py

44 lines
1.1 KiB
Python
Raw Normal View History

2016-02-26 11:39:01 +00:00
from threading import Lock
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 = {}
2016-02-26 11:39:01 +00:00
self._lock = {}
def lock(self, key):
if key not in self._lock:
self._lock[key] = Lock()
self._lock[key].acquire()
2014-05-26 11:41:59 +00:00
def get(self, key):
2016-02-15 14:13:40 +00:00
now = time.time()
2016-02-18 11:40:54 +00:00
for k, value in list(self._added.items()):
2016-02-15 14:13:40 +00:00
if value < now:
2016-02-23 15:21:26 +00:00
self._added.pop(k, None)
self.pop(k, None)
2016-02-26 11:39:01 +00:00
self._lock.pop(k, None)
if key in self._lock:
self._lock[key].acquire()
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)
2016-02-26 11:39:01 +00:00
q = self._lock.pop(key, None)
if q:
q.release()
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)