Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Django cache for certain app or page

Tags:

caching

django

Is there any possibility to clear cache for certain app in django or for certain page? I've tried to find it but in vain.

Thanks in advance.

like image 244
sepulchered Avatar asked Oct 25 '22 01:10

sepulchered


1 Answers

Something like this might help you..

    from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS
from django.utils.cache import get_cache_key, _generate_cache_header_key, _generate_cache_key
from django.core.urlresolvers import reverse
from django.http import HttpRequest
from django.conf import settings

def expire_cache(path, args=[], cache_name=None, isview=True, lang_code=None, method='GET'):
    if cache_name is None:
        cache_name = DEFAULT_CACHE_ALIAS

    cache = get_cache(cache_name)
    key_prefix = settings.CACHES[cache_name].get('KEY_PREFIX', '')

    request = HttpRequest()
    if isview:
        request.path = reverse(path, args=args)
    else:
        request.path = path

    language_code = lang_code or getattr(settings, 'LANGUAGE_CODE')
    if language_code:
        request.LANGUAGE_CODE = language_code

    header_key = _generate_cache_header_key(key_prefix, request)

    if not header_key:
        return False

    headerlist = cache.get(header_key, None)
    if headerlist is not None:
        cache.set(header_key, None, 0)
        page_key = _generate_cache_key(request, method, headerlist, key_prefix)

        if not page_key:
            return False

        cache.set(page_key, None, 0)
    return True

expire_cache('apps.yourapp.views.function') 
like image 169
xeor Avatar answered Oct 27 '22 11:10

xeor