Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ZSetCacheFilter:
- def __init__(self, cache_key: str, timeout: Union[float, int] = None, cache_name: str = "default"):
- self.cache: Redis = get_redis_connection(cache_name)
- self.cache_key = cache_key
- self.timeout = timeout
- @property
- def now(self):
- return time()
- def add(self, item):
- self.cache.zadd(self.cache_key, {item: self.now})
- def remove(self, item, *items):
- self.cache.zrem(self.cache_key, item, *items)
- def clean(self, max_time: Union[float, int] = None):
- if max_time is None:
- max_time = self.now - self.timeout
- self.cache.zremrangebyscore(self.cache_key, 0, max_time)
- def __contains__(self, item):
- score = self.cache.zscore(self.cache_key, item)
- if score is None:
- return False
- if score < self.now - self.timeout:
- return False
- return True
- def __enter__(self):
- return self
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement