Spaces:
Runtime error
Runtime error
| from functools import wraps | |
| from flask import current_app, jsonify | |
| import redis | |
| import json | |
| from datetime import datetime | |
| # 初始化Redis连接 | |
| redis_client = redis.Redis( | |
| host='localhost', | |
| port=6379, | |
| db=0, | |
| decode_responses=True | |
| ) | |
| def cache_key(*args, **kwargs): | |
| """生成缓存key""" | |
| return f"inventory_system:{args}:{sorted(kwargs.items())}" | |
| def cache(timeout=300): | |
| """缓存装饰器""" | |
| def decorator(f): | |
| def decorated_function(*args, **kwargs): | |
| key = cache_key(f.__name__, *args, **kwargs) | |
| # 尝试从缓存获取 | |
| cached_result = redis_client.get(key) | |
| if cached_result: | |
| return json.loads(cached_result) | |
| # 执行原函数 | |
| result = f(*args, **kwargs) | |
| # 存入缓存 | |
| redis_client.setex( | |
| key, | |
| timeout, | |
| json.dumps(result) | |
| ) | |
| return result | |
| return decorated_function | |
| return decorator | |
| def clear_cache(pattern="inventory_system:*"): | |
| """清除指定模式的缓存""" | |
| for key in redis_client.scan_iter(pattern): | |
| redis_client.delete(key) |