Skip to content

A Django app that provides a new cache on every request object. The cache is only kept within the request/response cycle.

License

Notifications You must be signed in to change notification settings

kobotoolbox/django-request-cache

 
 

Repository files navigation

Django Request Cache

https://github.com/anexia/django-request-cache/actions/workflows/test.yml/badge.svg?branch=main

Django Request Cache provides a cache for each request (within your Django Request/Response cycle).

Quick start

  1. Download and install using pip install
pip install django-request-cache
  1. Add UserForeignKeyMiddleware and RequestCacheMiddleware to your MIDDLEWARE settings like this:
MIDDLEWARE = (
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
    'django_userforeignkey.middleware.UserForeignKeyMiddleware',
    'django_request_cache.middleware.RequestCacheMiddleware',
)

or if you are still using the an older Django version (e.g., Django 1.8) with MIDDLEWARE_CLASSES:

MIDDLEWARE_CLASSES = (
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
    'django_userforeignkey.middleware.UserForeignKeyMiddleware',
    'django_request_cache.middleware.RequestCacheMiddleware',
)
  1. Use the per-request cache as a decorator
from django_request_cache import cache_for_request

@cache_for_request
def do_some_complex_calculation(a, b, c):
    print("Calculating... please wait")
    return a * b * c

Try it out by executing do_some_complex_calculation multiple times within your request

Attribution

RequestCache and RequestCacheMiddleware (see middleware.py) are from a source code snippet on StackOverflow https://stackoverflow.com/questions/3151469/per-request-cache-in-django/37015573#37015573 created by coredumperror https://stackoverflow.com/users/464318/coredumperror Original Question was posted by https://stackoverflow.com/users/7679/chase-seibert at https://stackoverflow.com/questions/3151469/per-request-cache-in-django copied on 2017-Dec-20

About

A Django app that provides a new cache on every request object. The cache is only kept within the request/response cycle.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%