cache-results

CI Coverage Latest release Python 3.10+ Django 4.2+ MIT License

cache-results is a Django decorator that caches a function’s results by its arguments, in any Django cache, such as Redis.

from cache_results import cache_results


@cache_results(timeout=600)
def get_book(book_id: int) -> dict:
    return Book.objects.values().get(pk=book_id)


get_book(42)             # computed and cached
get_book(42)             # served from the cache
get_book.invalidate(42)  # clears that entry

Features

  • Safe keys. The key is the function’s module and qualified name, plus a hash of its arguments bound to its signature. Arguments that can’t be part of a safe key run the function uncached, rather than be keyed by str().

  • None is cached like any other result.

  • Invalidation: every decorated function has an invalidate() that clears the entry of the same arguments.

  • async functions are cached without blocking the event loop.

  • Classmethods are cached per class. Instance methods are refused.

  • No stampede within a process: threads that miss the same key wait for the first one to compute it.

  • Safe during startup: a function called before Django’s apps are ready runs uncached.

  • One setting, CACHE_RESULTS, configures the cache, the timeout, keys and logging.

  • Small: depends only on Django and asgiref. MIT licensed.

Indices