Django Cache Memoize

0.2.1 · active · verified Thu Apr 16

django-cache-memoize is a Django utility that provides a memoization decorator, `cache_memoize`, which leverages the Django cache framework. It's designed to cache function call results, supports invalidation, and works with complex arguments and keyword arguments. The current version is 0.2.1, and it maintains an active release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `cache_memoize` decorator on an expensive function within a minimal Django setup. It configures a local memory cache, applies the decorator with a timeout, and shows how subsequent calls with the same arguments retrieve cached results. It also illustrates how to manually invalidate a specific cached entry.

import random
from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse
from cache_memoize import cache_memoize

# Minimal Django settings for cache configuration
if not settings.configured:
    settings.configure(
        CACHES={
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
                'LOCATION': 'unique-snowflake',
            }
        }
    )

# Example of a function that would be expensive
@cache_memoize(timeout=60 * 5) # Cache for 5 minutes
def expensive_calculation(a, b):
    print(f"Calculating for {a}, {b}...") # This will only print on cache miss
    return a + b + random.randint(0, 100)

# Example Django view
def my_view(request):
    result1 = expensive_calculation(10, 20)
    result2 = expensive_calculation(10, 20) # This should be a cache hit
    result3 = expensive_calculation(1, 2)

    # Invalidate cache for specific arguments
    # expensive_calculation.invalidate(10, 20)
    # print("Invalidated (10, 20)")
    # result_after_invalidation = expensive_calculation(10, 20)

    return HttpResponse(
        f"Result 1 (10, 20): {result1}<br>" +
        f"Result 2 (10, 20) (cached): {result2}<br>" +
        f"Result 3 (1, 2): {result3}<br>" +
        f"Cache key for (10, 20): {expensive_calculation.get_memoize_key(10, 20)}"
    )

# To run this, you would integrate it into a Django project's urls.py
# e.g., path('my_cached_view/', my_view),
# and ensure Django's cache settings are configured (as above or in settings.py)

view raw JSON →