gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
you are an expert in python. use best practices and refactor, find and fix all the bugs…
- User
you are an expert in python. use best practices and refactor, find and fix all the bugs in the following code
pythonimport asyncio from typing import Type, Callable from pydantic import BaseModel import functools import orjson from fastapi.encoders import jsonable_encoder # Assuming redis_client and settings are defined elsewhere class CacheResponse: def __init__(self, include_params: list[str] | None = None, exclude_params: list[str] | None = None): self.include_params = include_params or [] self.exclude_params = exclude_params or [] self.locks = {} # A dictionary to hold locks for each unique key def __call__(self, schema: Type[BaseModel] | None = None, ttl: int = settings.REDIS_TIMEOUT, include_params: list[str] | None = None, exclude_params: list[str] | None = None): def decorator(func: Callable): @functools.wraps(func) async def wrapper(*args, **kwargs): # generate the key for the function signature key = generate_key( func, include_params or self.include_params, exclude_params or self.exclude_params, *args, **kwargs, ) # Get or create a lock for the key lock = self.locks.setdefault(key, asyncio.Lock()) async with lock: cached_response = await redis_client.get_by_key(key) if cached_response: cached_response = orjson.loads(cached_response) if schema: if isinstance(cached_response, list): return [schema.parse_obj(r) for r in cached_response] else: return schema.parse_obj(cached_response) else: return cached_response else: if asyncio.iscoroutinefunction(func): response = await func(*args, **kwargs) else: response = func(*args, **kwargs) data = redis_client.RedisData( key=key, value=orjson.dumps(jsonable_encoder(response)), ttl=ttl ) await redis_client.set_redis_key(data) return response # Clean up the lock if it's no longer needed if key in self.locks and not lock.locked(): del self.locks[key] return wrapper return decorator cache_response = CacheResponse() - Assistant