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 814B

1234567891011121314151617181920212223242526
  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