实现缓存装饰器,优化数据获取和存储逻辑

This commit is contained in:
2025-02-22 13:38:16 +08:00
parent e1bc81c9e1
commit aaa4056482
2 changed files with 53 additions and 31 deletions

View File

@ -2,14 +2,36 @@ from .instances import cache
def from_cache(key):
"""
当缓存中有数据时,直接返回缓存中的数据,否则执行函数并将结果存入缓存
"""
def decorator(func):
def wrapper(*args, **kwargs):
async def wrapper(*args, **kwargs):
cached = cache.get(key)
if cached:
return cached
else:
result = func(*args, **kwargs)
result = await func(*args, **kwargs)
cache.set(key, result)
return result
return wrapper
return decorator
def update_to_cache(key):
"""
执行函数并将结果存入缓存
"""
def decorator(func):
async def wrapper(*args, **kwargs):
result = await func(*args, **kwargs)
cache.set(key, result)
return result
return wrapper
return decorator