Last active
September 8, 2017 20:28
-
-
Save andr1an/307af341e0cb71561b0f561647b75cac to your computer and use it in GitHub Desktop.
Python example of how to use Redis for caching
This file contains 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
"""Library to use Redis for the cache. | |
Usage: | |
from redis_cache import redis_cached | |
@redis_cached | |
def foo(bar, baz, misc=123): | |
return bar + baz + misc | |
""" | |
import hashlib | |
import json | |
from functools import wraps | |
import redis | |
CACHE_EXPIRY = 60 * 60 * 24 # 1 day | |
def _get_cache_key(function_name, *args, **kwargs): | |
"""Returns the key to use in Redis. | |
Uses {function_name}:{args_hash} format; | |
args_hash is the MD5 digest of JSON-serialized arguments. | |
""" | |
hasher = hashlib.md5() | |
hasher.update(json.dumps([args, kwargs])) | |
return '{function_name}:{args_hash}'.format( | |
function_name=function_name, | |
args_hash=hasher.hexdigest() | |
) | |
def redis_cached(func): | |
"""Decorator for caching functions results in Redis.""" | |
cache = redis.Redis() # TODO: your connect params here | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
"""Tries to get result from the cache, else calculates it and saves.""" | |
cache_key = _get_cache_key(func.__name__, *args, **kwargs) | |
result = cache.get(cache_key) | |
if result is not None: | |
return result | |
result = func(*args, **kwargs) | |
cache.set(cache_key, result, ex=CACHE_EXPIRY) | |
return result | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment