I'm trying to invalidate a view following this Expire a view-cache in Django?.
Here's a view function where I have disabled per-site
caching and enabled per-view
caching.
This is the view, say, that I need to invalidate.
@api_view(["GET"])
@never_cache
@cache_page(60*60)
def get_segment_list(request, appid: str, page: str) -> JsonResponse:
try:
...
I have already called get_segment_list
once and that has cached the response header and page.
127.0.0.1:6379> keys *
1) ":1:views.decorators.cache.cache_page..GET.39679326f007515994e08d99042c26f7.d41d8cd98f00b204e9800998ecf8427e.en-us.UTC"
2) ":1:views.decorators.cache.cache_header..39679326f007515994e08d99042c26f7.en-us.UTC". <<-- NOTE THIS
Here's a expire-view
function.
def expire_view_cache(view_name, args=[], namespace=None, key_prefix=None):
"""
This function allows you to invalidate any view-level cache.
view_name: view function you wish to invalidate or it's named url pattern
args: any arguments passed to the view function
namepace: optional, if an application namespace is needed
key prefix: for the @cache_page decorator for the function (if any)
"""
from django.urls import reverse
from django.http import HttpRequest
from django.utils.cache import get_cache_key
from django.core.cache import cache
# create a fake request object
request = HttpRequest()
# lookup the request path:
if namespace:
view_name = namespace + ":" + view_name
request.META = {
'SERVER_NAME': '1.0.0.127.in-addr.arpa',
'SERVER_PORT': 8000,
}
request.LANGUAGE_CODE = 'en-us'
request.path = reverse(view_name, kwargs=args)
# get cache key, expire if the cached item exists:
key = get_cache_key(request, method='GET', key_prefix=key_prefix)
if key:
if cache.get(key):
# Delete the cache entry.
cache.set(key, None, 0)
return True
return False
request.META
details are copied from the previous request
object while caching get_segment_list
.
But in expire_view_cache
a different cache_header
key is generated.
'views.decorators.cache.cache_header..9a20b800712b08ba816e521ea6b8081d.en-us.UTC'
This could probably be due to different request
headers but I am clueless as to what is missing from the fake request.
Any help is appreciated.