Last active
December 22, 2021 23:46
-
-
Save monkut/c20fe3b151e2904d6caa8f2044012211 to your computer and use it in GitHub Desktop.
A lazy implementation of an lru-ish redis based cache 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 json | |
from functools import wraps | |
import redis | |
REDIS_HOST = 'localhost' | |
REDIS_PORT = 6379 | |
REDIS_CONNECTION_POOL = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT) | |
CACHE_EXPIRE_SECONDS = 5000 | |
def redis_lru_cache(expire_seconds=CACHE_EXPIRE_SECONDS): | |
def decorator(func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
# check cached value | |
passed_arguments = args + tuple(sorted(kwargs.items())) | |
serialized_arguments = json.dumps(passed_arguments) | |
key = f'redis_lru_cache:{func.__name__}:{serialized_arguments}' | |
client = redis.StrictRedis(connection_pool=REDIS_CONNECTION_POOL) | |
serialized_result = client.get(key) | |
if not serialized_result: | |
print('cache miss') | |
result = func(*args, **kwargs) | |
serialized_resuilt = json.dumps(result).encode('utf8') | |
client.set(key, serialized_result) | |
else: | |
print('cache hit') | |
if serialized_result == b'None': | |
result = None | |
else: | |
result = json.loads(serialized_result) | |
print(f'> {result}') | |
client.expire(key, expire_seconds) | |
return result | |
return wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment