Login

A wrapper around cache_page making it optional

Author:
rixx
Posted:
January 22, 2022
Language:
Python
Version:
3.2
Score:
1 (after 1 ratings)

Make cache_page optional, depending on the result of a callable. Uncomment the added lines if you want to make sure that the consumers don't know the page is cached – that means more hits on your end, but also a guarantee that they will always get the newest data asap.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def conditional_cache_page(timeout, condition, *, cache=None, key_prefix=None):
    """This decorator is exactly like cache_page, but with the option to skip
    the caching entirely.

    The second argument is a callable, ``condition``. It's given the
    request and all further arguments, and if it evaluates to a true-ish
    value, the cache is used.
    """

    def decorator(func):
        def wrapper(request, *args, **kwargs):
            if condition(request, *args, **kwargs):
                response = cache_page(
                    timeout=timeout, cache=cache, key_prefix=key_prefix
                )(func)(request, *args, **kwargs)
                # If you don't want consumers to know that the page is cached, add these:
                # response.headers.pop("Expires")
                # response.headers.pop("Cache-Control")

            return func(request, *args, **kwargs)
        return wrapper
    return decorator

More like this

  1. LazyPrimaryKeyRelatedField by LLyaudet 2 days, 18 hours ago
  2. CacheInDictManager by LLyaudet 3 days, 1 hour ago
  3. MYSQL Full Text Expression by Bidaya0 3 days, 19 hours ago
  4. Custom model manager chaining (Python 3 re-write) by Spotted1270 1 week, 3 days ago
  5. Django Standard API Response Middleware for DRF for modern frontend easy usage by Denactive 3 weeks, 4 days ago

Comments

Please login first before commenting.