Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cache for Django model properties.
from __future__ import unicode_literals
import functools
from django.core.cache import cache
class cached(object):
"""Save the return of the function on the cache.
"""
def __init__(self, timeout=None, model=None):
self.timeout = timeout
self.model = model
def __call__(self, func):
@functools.wraps(func)
def decorated(instance, *args, **kwargs):
if self.model is None:
self.model = instance._meta.model_name
# Set the cache name
self.cache_name = '{}_{}'.format(self.model, func.__name__)
# Check if the cache exists
if cache.get(self.cache_name) is None:
cache_dict = {}
else:
cache_dict = cache.get(self.cache_name)
# Check if the result for the current is cached
if instance.pk in cache_dict:
# Return the cached result
return cache_dict[instance.pk]
# Calculate the value of the current method
val = func(instance, *args, **kwargs)
# Update the cache dictionary of values with the new value
cache_dict[instance.pk] = val
# Save the cache
cache.set(self.cache_name, cache_dict, self.timeout)
# Return the calculated value
return val
# Execute the callback
return decorated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment