-
-
Save mike-douglas/4353847 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
from hashlib import sha1 | |
from redis import Redis | |
import json | |
def redis_memoize(cache, conn=None): | |
"""Decorator to cache function calls in redis. Stores as JSON so the data is somewhat portable""" | |
class _decorator(object): | |
def __init__(self, func): | |
self.func = func | |
self.redis = conn if not conn is None else Redis() | |
def __call__(self, *args, **kwargs): | |
key = self.hash(args, kwargs) | |
if self.redis.hexists(cache, key): | |
return json.loads(self.redis.hget(cache, key)) | |
else: | |
value = self.func(*args, **kwargs) | |
self.redis.hset(cache, key, json.dumps(value)) | |
return value | |
def hash(self, a, b): | |
return sha1(json.dumps(a) + json.dumps(b)).hexdigest() | |
return _decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment