Browse Source

fix: time type bug

master
zhayujie 1 year ago
parent
commit
e071b6c1b4
1 changed files with 8 additions and 9 deletions
  1. +8
    -9
      common/expired_dict.py

+ 8
- 9
common/expired_dict.py View File

@@ -1,6 +1,6 @@
import time
from datetime import datetime, timedelta from datetime import datetime, timedelta



class ExpiredDict(dict): class ExpiredDict(dict):
def __init__(self, expires_in_seconds): def __init__(self, expires_in_seconds):
super().__init__() super().__init__()
@@ -8,8 +8,7 @@ class ExpiredDict(dict):


def __getitem__(self, key): def __getitem__(self, key):
value, expiry_time = super().__getitem__(key) value, expiry_time = super().__getitem__(key)
# 如果元素已过期,则从字典中删除该元素并抛出 KeyError 异常
if time.monotonic() > expiry_time:
if datetime.now() > expiry_time:
del self[key] del self[key]
raise KeyError("expired {}".format(key)) raise KeyError("expired {}".format(key))
self.__setitem__(key, value) self.__setitem__(key, value)
@@ -24,20 +23,20 @@ class ExpiredDict(dict):
return self[key] return self[key]
except KeyError: except KeyError:
return default return default
def __contains__(self, key): def __contains__(self, key):
try: try:
self[key] self[key]
return True return True
except KeyError: except KeyError:
return False return False
def keys(self): def keys(self):
keys=list(super().keys())
keys = list(super().keys())
return [key for key in keys if key in self] return [key for key in keys if key in self]
def items(self): def items(self):
return [(key, self[key]) for key in self.keys()] return [(key, self[key]) for key in self.keys()]
def __iter__(self): def __iter__(self):
return self.keys().__iter__()
return self.keys().__iter__()

Loading…
Cancel
Save