NDOJ/judge/caching.py

53 lines
1.6 KiB
Python
Raw Normal View History

2023-04-05 17:49:23 +00:00
from inspect import signature
2020-01-21 06:35:58 +00:00
from django.core.cache import cache
2023-04-05 17:49:23 +00:00
from django.db.models.query import QuerySet
2020-01-21 06:35:58 +00:00
2023-04-05 17:49:23 +00:00
import hashlib
2020-01-21 06:35:58 +00:00
2023-04-05 17:49:23 +00:00
MAX_NUM_CHAR = 15
2023-08-29 23:36:01 +00:00
NONE_RESULT = "__None__"
2023-04-05 17:49:23 +00:00
2023-08-29 23:36:01 +00:00
def cache_wrapper(prefix, timeout=None):
2023-04-05 17:49:23 +00:00
def arg_to_str(arg):
if hasattr(arg, "id"):
return str(arg.id)
if isinstance(arg, list) or isinstance(arg, QuerySet):
return hashlib.sha1(str(list(arg)).encode()).hexdigest()[:MAX_NUM_CHAR]
if len(str(arg)) > MAX_NUM_CHAR:
return str(arg)[:MAX_NUM_CHAR]
return str(arg)
def get_key(func, *args, **kwargs):
args_list = list(args)
signature_args = list(signature(func).parameters.keys())
args_list += [kwargs.get(k) for k in signature_args[len(args) :]]
args_list = [arg_to_str(i) for i in args_list]
key = prefix + ":" + ":".join(args_list)
key = key.replace(" ", "_")
return key
def decorator(func):
def wrapper(*args, **kwargs):
cache_key = get_key(func, *args, **kwargs)
result = cache.get(cache_key)
if result is not None:
2023-08-29 23:36:01 +00:00
if result == NONE_RESULT:
result = None
2023-04-05 17:49:23 +00:00
return result
2023-08-29 23:36:01 +00:00
if result is None:
result = NONE_RESULT
2023-04-05 17:49:23 +00:00
result = func(*args, **kwargs)
cache.set(cache_key, result, timeout)
return result
def dirty(*args, **kwargs):
cache_key = get_key(func, *args, **kwargs)
cache.delete(cache_key)
wrapper.dirty = dirty
return wrapper
return decorator