Skip to content

Instantly share code, notes, and snippets.

@siarheidevel
Last active November 10, 2022 06:33
Show Gist options
  • Save siarheidevel/ab0cd75af033ac8fb20417df06a2e326 to your computer and use it in GitHub Desktop.
Save siarheidevel/ab0cd75af033ac8fb20417df06a2e326 to your computer and use it in GitHub Desktop.
Caching decorator
import functools, logging, inspect
def cached(key:str, timeout_sec: int = 5 * 60):
"""
key - cache_key_{param1_name}_{param2_name}
timeout_sec - timeout in seconds
"""
def inner_function(function):
@functools.wraps(function)
def wrapper_cache_func(*args, **kwargs):
bound_args = inspect.signature(function).bind(*args, **kwargs)
bound_args.apply_defaults()
generated_key = key.format(**bound_args.arguments)
try:
result = cache.get_by_key(generated_key)
if result is None:
logger.warning(f'Not in cache {function.__name__}{args[:1]} ')
result = function(*args, **kwargs)
cache.set_by_key(generated_key, result, timeout=timeout_sec)
return result
except Exception as e:
logger.exception(f'Exception in cached {function.__name__}{args[:1]} ')
raise e
return wrapper_cache_func
return inner_function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment