I'm trying to purge cache for one specific Entry when it is saved using signals.
I'm using decorators (signals
and render_to
) from django-annoying
@signals.post_save(sender=Artigo)
def artigo_post_save(instance, **kwargs):
from django.http import HttpRequest
from django.utils.cache import get_cache_key
from django.core.cache import cache
# cache.delete(instance.get_absolute_url()) # not work
request = HttpRequest()
request.method = "GET"
request.path = '/' + instance.get_absolute_url()
print 'request path: ', request.path
key = get_cache_key(request=request,
key_prefix=settings.CACHE_MIDDLEWARE_KEY_PREFIX)
print "found key" if cache.has_key(key) else "notfound key"
if cache.has_key(key):
cache.delete(key)
cache.set(key, None, 0)
"notfound key"
, so the cache continues without purgerequest.path
are point properly to my entry path.Some settings:
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
CACHE_MIDDLEWARE_KEY_PREFIX = 'cache'
CACHE_MIDDLEWARE_SECONDS = 600
CACHES = {
'default': {
'LOCATION': '',
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
},
}
And the view:
@cache_page(60 * 60)
@render_to('artigo.html')
def artigo(request, categoria_slug, extra_slug="", artigo_slug=""):
...
Thank you.
EDIT:
I did Ilvar changes and now i'm getting "found key"
as return but I still can't delete cache:
key = _generate_cache_header_key(key_prefix=settings.CACHE_MIDDLEWARE_KEY_PREFIX, request=request)
key = key.replace(settings.LANGUAGE_CODE, settings.LANGUAGES[0][0])
Conf:
LANGUAGE_CODE = 'pt-BR'
LANGUAGES = (
('pt-BR','Portugues'),
)
cache.set(key, None, 0) should be enough, I've been clearing cache keys that way before.
If you are able to, can you try the cache.clear(), to clear it all? Just to see if it works.
Are non of your cache keys deletable? Is the output of this as expected?
cache.set('testkey', 'testvalue', 600)
cache.get('testkey')
cache.delete('testkey')
cache.get('testkey')
cache.set('testkey', 'testvalue2', 600)
cache.set('testkey', 'another value', 600)
cache.get('testkey')
And have you tried with another caching backend? It looks like everything you are doing is correct.
Maybe the error is in the backend, some configuration that wont let it overwrite keys or something weird..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With