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.

27 lines
814B

  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. # 刷新元素缓存时间
  16. super().__setitem__(key, (value, time.monotonic() + self.expires_in_seconds))
  17. def get(self, key, default=None):
  18. try:
  19. return self[key]
  20. except KeyError:
  21. return default