, , . Python:
class ExpiringCache(BaseCache):
"""A cache that allows you to update values without changing when the
data will expire. We do this by storing when the value was
inserted in the cache and decrementing the timeout when we update.
"""
def get(self, key, *args, **kwargs):
raw_value = super(ExpiringCache, self).get(key, *args, **kwargs)
if raw_value is None:
return None
value, start_time, timeout = raw_value
return value
def set(self, key, value, *args, **kwargs):
timeout = kwargs.get('timeout')
raw_value = (value, now(), timeout)
super(ExpiringCache, self).set(key, raw_value, *args, **kwargs)
def update(self, key, value, timeout=None):
"""If this value is still in the cache, update it but reduce the
timeout. If it not present, just set it.
"""
raw_value = super(ExpiringCache, self).get(key)
if raw_value is None:
self.set(key, value, timeout=timeout)
return
original_value, start_time, original_timeout = raw_value
if not original_timeout:
self.set(key, value, timeout=original_timeout)
return
elapsed_time = (now() - start_time).total_seconds()
remaining_timeout = timeout - elapsed_time
if remaining_timeout > 0:
self.set(key, value, timeout=remaining_timeout)