Created
April 29, 2013 21:18
-
-
Save correl/5484859 to your computer and use it in GitHub Desktop.
Caching decorator (AOP?!)
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
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