Skip to content

Instantly share code, notes, and snippets.

@mike-douglas
Forked from anonymous/gist:4353836
Created December 21, 2012 16:30
Show Gist options
  • Save mike-douglas/4353847 to your computer and use it in GitHub Desktop.
Save mike-douglas/4353847 to your computer and use it in GitHub Desktop.
#!/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