graph_show / app /cache.py
huanghehe1223's picture
Upload 26 files
3154536 verified
import time
from functools import wraps
import json
class MemoryCache:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(MemoryCache, cls).__new__(cls)
cls._instance.cache = {}
cls._instance.timestamps = {}
return cls._instance
def get(self, key):
"""获取缓存,检查是否过期"""
if key in self.cache:
timestamp = self.timestamps.get(key, 0)
if timestamp > time.time():
return self.cache[key]
else:
# 过期则删除
self.delete(key)
return None
def set(self, key, value, expiration=86400):
"""设置缓存,带过期时间"""
self.cache[key] = value
self.timestamps[key] = time.time() + expiration
def delete(self, key):
"""删除缓存"""
if key in self.cache:
del self.cache[key]
if key in self.timestamps:
del self.timestamps[key]
def clear_by_prefix(self, prefix):
"""按前缀清除缓存"""
to_delete = [k for k in self.cache.keys() if k.startswith(prefix)]
for key in to_delete:
self.delete(key)
def get_cache_info(self, key):
"""获取缓存信息"""
if key in self.cache and key in self.timestamps:
return {
"exists": True,
"expires_at": self.timestamps[key],
"expires_in": int(self.timestamps[key] - time.time())
}
return {"exists": False}
def clear_all(self):
"""清除所有缓存"""
self.cache.clear()
self.timestamps.clear()
# 创建缓存实例
cache = MemoryCache()