您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

expired_dict.py 764B

1234567891011121314151617181920212223
  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