Skip to content

Commit

Permalink
Merge pull request #250 from synfinner/dev
Browse files Browse the repository at this point in the history
Adjust caching key strategy, per bug #249
  • Loading branch information
synfinner authored Dec 9, 2024
2 parents 2764fcc + fad6d53 commit e1530b8
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions utils/cache_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,30 @@ def kev_cache(timeout=120, key_prefix="cache_", query_string=False):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
cache_key = f"{key_prefix}{func.__name__}_"
cache_key += "_".join([str(arg) for arg in args]) + "_"
cache_key += "_".join([f"{k}_{v}" for k, v in kwargs.items()])
# Skip self (args[0]) if this is a method
method_args = args[1:] if args and hasattr(args[0], '__class__') else args

key_parts = [key_prefix, func.__name__]
if method_args:
args_hash = hashlib.sha256(
json.dumps(method_args, sort_keys=True, cls=jencoder).encode('utf-8')
).hexdigest()
key_parts.append(f"args_{args_hash}")

if kwargs:
kwargs_hash = hashlib.sha256(
json.dumps(dict(sorted(kwargs.items())), cls=jencoder).encode('utf-8')
).hexdigest()
key_parts.append(f"kwargs_{kwargs_hash}")

cache_key = "_".join(key_parts)

if query_string:
from flask import request
query_params = str(sorted(request.args.items()))
cache_key += f"_query_{hash(query_params)}"
# Use a hash to avoid adding unsafe chars directly
query_hash = hashlib.sha256(query_params.encode('utf-8')).hexdigest()
cache_key += f"_query_{query_hash}"

# Sanitize the generated cache key
cache_key = sanitize_cache_key(cache_key)
Expand All @@ -126,6 +142,5 @@ def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
cache_manager.set(cache_key, result, timeout=timeout)
return result

return wrapper
return decorator

0 comments on commit e1530b8

Please sign in to comment.