Created
February 23, 2014 20:00
-
-
Save carymrobbins/9176469 to your computer and use it in GitHub Desktop.
Yet another function cache decorator for Django.
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
| from functools import wraps | |
| from django.core.cache import cache | |
| def cached(key, timeout=None): | |
| """Decorator to cache result of function call for timeout seconds if the | |
| result is not None. | |
| """ | |
| def wrapper(f): | |
| @wraps(f) | |
| def wrapped(*args, **kwargs): | |
| result = cache.get(key) | |
| if result is not None: | |
| return result | |
| result = f(*args, **kwargs) | |
| if result is not None: | |
| cache.set(key, result, timeout) | |
| return result | |
| return wrapped | |
| return wrapper | |
| # Example usage: | |
| @cached('foo-data', 5) | |
| def foo(shout): | |
| print('About to shout {!r}'.format(shout)) | |
| return '{}!'.format(shout) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment