Created
March 19, 2014 11:52
-
-
Save chesster/9640131 to your computer and use it in GitHub Desktop.
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 recurly as recurly_api | |
from django.core.cache import cache | |
from django.conf import settings | |
from hashlib import sha512 | |
def string_to_key(string): | |
return sha512(string).hexdigest()[:250] # max size of caching keys in memcached | |
def function_cache(timeout=300, override_key=None): | |
def decorator(func): | |
def wrapper(*args, **kwargs): | |
if not timeout: | |
return func(*args, **kwargs) | |
if override_key: | |
cache_key = string_to_key(override_key) | |
else: | |
caching_keys = [func.__name__] | |
if args is not None: | |
caching_keys.extend(args) | |
if kwargs is not None: | |
caching_keys.extend(sorted(kwargs.iteritems())) | |
caching_keys = map(str, caching_keys) | |
cache_key = '_'.join(caching_keys) | |
cache_key = string_to_key(cache_key) | |
output = cache.get(cache_key) | |
if output is None: | |
output = func(*args, **kwargs) | |
cache.set(cache_key, output, timeout) | |
return output | |
return wrapper | |
return decorator | |
class CachedObject(object): | |
CACHE_TIME = 60*60*24 | |
CACHED_ATRIBUTES = () | |
def __getattr__(self, name, skip_cache=False): | |
if not skip_cache and name in self.CACHED_ATRIBUTES: | |
@function_cache(self.CACHE_TIME, "%s%s" % (self.__class__, name)) | |
def cache_getattr(obj, name): | |
return obj.__getattr__(name, True) | |
return cache_getattr(self, name) | |
else: | |
return super(CachedObject, self).__getattr__(name) | |
def __setattr__(self, name, value): | |
if name in self.CACHED_ATRIBUTES: | |
cache.set(string_to_key("%s%s" % (self.__class__, name)), value, self.CACHE_TIME) | |
return super(CachedObject, self).__setattr__(name, value) | |
class CachedAccount(CachedObject, recurly_api.Account): | |
CACHE_TIME = 60*60*24 | |
CACHED_ATRIBUTES = ('billing_info',) | |
def __init__(self, *args, **kwargs): | |
super(CachedAccount, self).__init__(*args, **kwargs) | |
@classmethod | |
@function_cache(CACHE_TIME) | |
def get(cls, uuid): | |
return super(CachedAccount, cls).get(uuid) | |
def update_billing_info(self, billing_info): | |
self.billing_info = billing_info | |
super(CachedAccount, self).update_billing_info(billing_info) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment