Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created February 23, 2014 20:00
Show Gist options
  • Save carymrobbins/9176469 to your computer and use it in GitHub Desktop.
Save carymrobbins/9176469 to your computer and use it in GitHub Desktop.
Yet another function cache decorator for Django.
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