Created
December 4, 2020 00:29
-
-
Save tubaman/ddbba1c64188bb555a7f3094f147c6b3 to your computer and use it in GitHub Desktop.
A python dictionary where the items timeout after self.timeout seconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
class CachedDict(object): | |
"""A dictionary where the items timeout after self.timeout seconds | |
We've implemented just enough of a real dictionary to work as a | |
replacement for the dicts in django.template.loader.cached.Loader | |
""" | |
def __init__(self, *args, **kwargs): | |
self.data = {} | |
try: | |
self.timeout = kwargs['timeout'] | |
except KeyError: | |
self.timeout = 300 # 5 min | |
def __setitem__(self, key, value): | |
timestamp = int(time.time()) | |
self.data[key] = (timestamp, value) | |
def __getitem__(self, key): | |
now = int(time.time()) | |
timestamp, value = self.data[key] | |
if now - timestamp > self.timeout: | |
del self.data[key] | |
raise KeyError(key) | |
return value | |
def get(self, key, default=None): | |
try: | |
return self.__getitem__(key) | |
except KeyError: | |
return default | |
def clear(self): | |
self.data.clear() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment