Last active
November 10, 2022 06:33
-
-
Save siarheidevel/ab0cd75af033ac8fb20417df06a2e326 to your computer and use it in GitHub Desktop.
Caching decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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