cache-results
cache-results is a Django decorator that caches a function’s results by its arguments, in any Django cache, such as Redis.
It is part of The Smarter Project. It began as the caching layer of Smarter, an open-source platform for building and running AI applications with Django, where it caches database reads and third-party api calls across many application servers.
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.
Getting Started
User Guide
Reference