Skip to content

Instantly share code, notes, and snippets.

@monkut
Last active December 22, 2021 23:46
Show Gist options
  • Save monkut/c20fe3b151e2904d6caa8f2044012211 to your computer and use it in GitHub Desktop.
Save monkut/c20fe3b151e2904d6caa8f2044012211 to your computer and use it in GitHub Desktop.
A lazy implementation of an lru-ish redis based cache decorator
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