Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

expired_dict.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import time
  2. from collections import OrderedDict
  3. class ExpiredDict(OrderedDict):
  4. def __init__(self, expires_in_seconds):
  5. super().__init__()
  6. # 存储键值对的生存时间
  7. self.expires_in_seconds = expires_in_seconds
  8. # 获取当前时间的函数
  9. self.now = time.monotonic
  10. def __getitem__(self, key):
  11. # 检查键是否存在
  12. if key not in self:
  13. raise KeyError(key)
  14. # 获取值和过期时间
  15. value, expiry_time = self[key]
  16. # 如果过期时间早于当前时间,删除该键值对并引发 KeyError
  17. if expiry_time is not None and self.now() > expiry_time:
  18. del self[key]
  19. raise KeyError(key)
  20. # 如果存活时间不为 None,更新该键值对的过期时间
  21. if self.expires_in_seconds is not None:
  22. self[key] = value, self.now() + self.expires_in_seconds
  23. # 删除过期的键值对
  24. self._delete_expired_items()
  25. # 返回值
  26. return value
  27. def __setitem__(self, key, value):
  28. # 如果存活时间不为 None,设置该键值对的过期时间
  29. if self.expires_in_seconds is not None:
  30. self[key] = value, self.now() + self.expires_in_seconds
  31. else:
  32. self[key] = value, None
  33. # 删除过期的键值对
  34. self._delete_expired_items()
  35. def get(self, key, default=None):
  36. try:
  37. return self[key]
  38. except KeyError:
  39. return default
  40. def _delete_expired_items(self):
  41. # 遍历所有键值对,删除过期的键值对
  42. for key, (value, expiry_time) in list(self.items()):
  43. if expiry_time is not None and self.now() > expiry_time:
  44. del self[key]