Skip to content

Instantly share code, notes, and snippets.

@correl
Created April 29, 2013 21:18
Show Gist options
  • Save correl/5484859 to your computer and use it in GitHub Desktop.
Save correl/5484859 to your computer and use it in GitHub Desktop.
Caching decorator (AOP?!)
def cached(key_formatstr):
def decorator(fn):
def wrapped(self, *args, **kwargs):
cache_key = key_formatstr.format(*args, **kwargs)
log.debug('Fetching cached value for {0}'.format(cache_key))
value = self.mc_get(cache_key)
if not value:
value = fn(self, *args, **kwargs)
log.debug('Storing cached value for {0}'.format(cache_key))
self.mc_set(cache_key, value)
return value
return wrapped
return decorator
class MyRPC:
@cached("user:{0}")
def get_user(user_id):
return requests.get("http://rest.myapi.com/user/{0}".format(user_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment