2016-05-31 20:48:19 +00:00
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
class ExpiresEntry(object):
|
|
|
|
""" A single entry under a ExpiresDict. """
|
|
|
|
def __init__(self, value, expires=None):
|
|
|
|
self.value = value
|
|
|
|
self._expiration = expires
|
|
|
|
|
|
|
|
@property
|
|
|
|
def expired(self):
|
|
|
|
if self._expiration is None:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return datetime.now() >= self._expiration
|
|
|
|
|
|
|
|
|
|
|
|
class ExpiresDict(object):
|
|
|
|
""" ExpiresDict defines a dictionary-like class whose keys have expiration. The rebuilder is
|
|
|
|
a function that returns the full contents of the cached dictionary as a dict of the keys
|
2018-05-01 10:25:46 +00:00
|
|
|
and whose values are TTLEntry's. If the rebuilder is None, then no rebuilding is performed.
|
2016-05-31 20:48:19 +00:00
|
|
|
"""
|
2018-05-01 10:25:46 +00:00
|
|
|
def __init__(self, rebuilder=None):
|
2016-05-31 20:48:19 +00:00
|
|
|
self._rebuilder = rebuilder
|
|
|
|
self._items = {}
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
found = self.get(key)
|
|
|
|
if found is None:
|
|
|
|
raise KeyError
|
|
|
|
|
|
|
|
return found
|
|
|
|
|
|
|
|
def get(self, key, default_value=None):
|
|
|
|
# Check the cache first. If the key is found and it has not yet expired,
|
|
|
|
# return it.
|
|
|
|
found = self._items.get(key)
|
|
|
|
if found is not None and not found.expired:
|
|
|
|
return found.value
|
|
|
|
|
|
|
|
# Otherwise the key has expired or was not found. Rebuild the cache and check it again.
|
2017-05-26 17:49:50 +00:00
|
|
|
items = self._rebuild()
|
|
|
|
found_item = items.get(key)
|
|
|
|
if found_item is None:
|
2016-05-31 20:48:19 +00:00
|
|
|
return default_value
|
|
|
|
|
2017-05-26 17:49:50 +00:00
|
|
|
return found_item.value
|
2016-05-31 20:48:19 +00:00
|
|
|
|
|
|
|
def __contains__(self, key):
|
|
|
|
return self.get(key) is not None
|
|
|
|
|
|
|
|
def _rebuild(self):
|
2018-05-01 10:25:46 +00:00
|
|
|
if self._rebuilder is None:
|
|
|
|
return self._items
|
|
|
|
|
2017-05-26 17:49:50 +00:00
|
|
|
items = self._rebuilder()
|
|
|
|
self._items = items
|
|
|
|
return items
|
2016-05-31 20:48:19 +00:00
|
|
|
|
|
|
|
def set(self, key, value, expires=None):
|
|
|
|
self._items[key] = ExpiresEntry(value, expires=expires)
|