40 lines
700 B
Python
40 lines
700 B
Python
"""
|
|
简单 TTL 缓存 - 纯 Python 3.8 stdlib
|
|
用于缓存 API 响应,减少数据库查询
|
|
"""
|
|
import time
|
|
|
|
_cache = {}
|
|
_cache_config = {}
|
|
|
|
|
|
def init_cache(config):
|
|
_cache_config.update(config)
|
|
|
|
|
|
def get(key):
|
|
if key in _cache:
|
|
data, expire = _cache[key]
|
|
if time.time() < expire:
|
|
return data
|
|
del _cache[key]
|
|
return None
|
|
|
|
|
|
def set(key, data, ttl=10):
|
|
_cache[key] = (data, time.time() + ttl)
|
|
|
|
|
|
def clear():
|
|
_cache.clear()
|
|
|
|
|
|
def invalidate(prefix=''):
|
|
"""按前缀清除缓存"""
|
|
if not prefix:
|
|
_cache.clear()
|
|
else:
|
|
keys = [k for k in _cache if k.startswith(prefix)]
|
|
for k in keys:
|
|
del _cache[k]
|