expired_dict.py 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from datetime import datetime, timedelta
  2. class ExpiredDict(dict):
  3. def __init__(self, expires_in_seconds):
  4. super().__init__()
  5. self.expires_in_seconds = expires_in_seconds
  6. def __getitem__(self, key):
  7. value, expiry_time = super().__getitem__(key)
  8. if datetime.now() > expiry_time:
  9. del self[key]
  10. raise KeyError("expired {}".format(key))
  11. self.__setitem__(key, value)
  12. return value
  13. def __setitem__(self, key, value):
  14. expiry_time = datetime.now() + timedelta(seconds=self.expires_in_seconds)
  15. super().__setitem__(key, (value, expiry_time))
  16. def get(self, key, default=None):
  17. try:
  18. return self[key]
  19. except KeyError:
  20. return default
  21. def __contains__(self, key):
  22. try:
  23. self[key]
  24. return True
  25. except KeyError:
  26. return False
  27. def keys(self):
  28. keys = list(super().keys())
  29. return [key for key in keys if key in self]
  30. def items(self):
  31. return [(key, self[key]) for key in self.keys()]
  32. def __iter__(self):
  33. return self.keys().__iter__()