Created
May 12, 2015 13:34
-
-
Save RodrigoEspinosa/b05e63e7fbfb82ac0aac to your computer and use it in GitHub Desktop.
Cache for Django model properties.
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
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