2016-05-31 09:36:22 +00:00
|
|
|
from datetime import datetime
|
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2016-10-22 12:43:52 +00:00
|
|
|
class LruCacheItem:
|
2016-05-31 09:36:22 +00:00
|
|
|
def __init__(self, key, value):
|
|
|
|
self.key = key
|
|
|
|
self.value = value
|
2016-07-03 12:46:15 +00:00
|
|
|
self.timestamp = datetime.utcnow()
|
2016-05-31 09:36:22 +00:00
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2016-10-22 12:43:52 +00:00
|
|
|
class LruCache:
|
2016-05-31 09:36:22 +00:00
|
|
|
def __init__(self, length, delta=None):
|
|
|
|
self.length = length
|
|
|
|
self.delta = delta
|
|
|
|
self.hash = {}
|
|
|
|
self.item_list = []
|
|
|
|
|
|
|
|
def insert_item(self, item):
|
|
|
|
if item.key in self.hash:
|
2016-08-14 12:22:53 +00:00
|
|
|
item_index = next(
|
|
|
|
i
|
|
|
|
for i, v in enumerate(self.item_list)
|
2016-06-02 21:39:26 +00:00
|
|
|
if v.key == item.key)
|
|
|
|
self.item_list[:] \
|
|
|
|
= self.item_list[:item_index] \
|
2016-08-14 12:22:53 +00:00
|
|
|
+ self.item_list[item_index + 1:]
|
2016-05-31 09:36:22 +00:00
|
|
|
self.item_list.insert(0, item)
|
|
|
|
else:
|
|
|
|
if len(self.item_list) > self.length:
|
|
|
|
self.remove_item(self.item_list[-1])
|
|
|
|
self.hash[item.key] = item
|
|
|
|
self.item_list.insert(0, item)
|
|
|
|
|
|
|
|
def remove_all(self):
|
|
|
|
self.hash = {}
|
|
|
|
self.item_list = []
|
|
|
|
|
|
|
|
def remove_item(self, item):
|
|
|
|
del self.hash[item.key]
|
|
|
|
del self.item_list[self.item_list.index(item)]
|
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2016-06-02 21:39:26 +00:00
|
|
|
_CACHE = LruCache(length=100)
|
2016-05-31 09:36:22 +00:00
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2016-05-31 09:36:22 +00:00
|
|
|
def purge():
|
2016-06-02 21:39:26 +00:00
|
|
|
_CACHE.remove_all()
|
2016-05-31 09:36:22 +00:00
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2016-05-31 09:36:22 +00:00
|
|
|
def has(key):
|
2016-06-02 21:39:26 +00:00
|
|
|
return key in _CACHE.hash
|
2016-05-31 09:36:22 +00:00
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2016-05-31 09:36:22 +00:00
|
|
|
def get(key):
|
2016-06-02 21:39:26 +00:00
|
|
|
return _CACHE.hash[key].value
|
2016-05-31 09:36:22 +00:00
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2016-08-27 10:39:59 +00:00
|
|
|
def remove(key):
|
|
|
|
if has(key):
|
|
|
|
del _CACHE.hash[key]
|
|
|
|
|
|
|
|
|
2016-05-31 09:36:22 +00:00
|
|
|
def put(key, value):
|
2016-06-02 21:39:26 +00:00
|
|
|
_CACHE.insert_item(LruCacheItem(key, value))
|