You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.2KB

  1. import time
  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. # 如果元素已过期,则从字典中删除该元素并抛出 KeyError 异常
  9. if time.monotonic() > expiry_time:
  10. del self[key]
  11. raise KeyError("expired {}".format(key))
  12. self.__setitem__(key, value)
  13. return value
  14. def __setitem__(self, key, value):
  15. expiry_time = datetime.now() + timedelta(seconds=self.expires_in_seconds)
  16. super().__setitem__(key, (value, expiry_time))
  17. def get(self, key, default=None):
  18. try:
  19. return self[key]
  20. except KeyError:
  21. return default
  22. def __contains__(self, key):
  23. try:
  24. self[key]
  25. return True
  26. except KeyError:
  27. return False
  28. def keys(self):
  29. keys=list(super().keys())
  30. return [key for key in keys if key in self]
  31. def items(self):
  32. return [(key, self[key]) for key in self.keys()]
  33. def __iter__(self):
  34. return self.keys().__iter__()