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. 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. # print(f'{key} 缓存过期时间:{expiry_time}')
  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__()