ruk·si

Django
Cache

Updated at 2018-06-22 20:03
from django.core.cache import cache

def get_heavy_data(id, use_cache=True):
    cache_key = f'heavy_data:{id}'
    heavy_data = (cache.get(cache_key) if use_cache else None)
    if not heavy_data:
        heavy_data = _get_heavy_data(id)
        cache.set(cache_key, heavy_data, timeout=60)
    return heavy_data

def _get_heavy_data(id):
    # do the expensive operation to get the data
    return {'id': id, 'name': 'John'}

# what to use as a cache is configured with settings.CACHES
# locmemcache is good for development but not for production
# as each process will maintain own cache