23 lines
764B

  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