0

I'm using memcached in Django to cache the entire site.

https://docs.djangoproject.com/en/1.11/topics/cache/#the-per-site-cache

I've added some code in a post-save signal handler method to clear the cache when certain objects are created or updated in the model.

from proximity.models import Advert

# Cache
from django.core.cache import cache

@receiver(post_save, sender=Advert)
def save_advert(sender, instance, **kwargs):
    # Clear cache
    cache.clear()

Unfortunately now after creating a new object, the user is logged out.

I think that the reason can be that I'm caching sessions.

# Cache config
CACHE_MIDDLEWARE_SECONDS = 31449600 #(approximately 1 year, in seconds)
CACHE_MIDDLEWARE_KEY_PREFIX = COREAPP
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.memcached.MemcachedCache",
        "LOCATION": "127.0.0.1:11211",
    }
}
SESSION_ENGINE = "django.contrib.sessions.backends.cache"

Should I use per-view cache maybe?

Martinez Mariano
  • 541
  • 8
  • 19
  • It's unclear what "cache entire site" is. – vishes_shell Jun 13 '17 at 12:07
  • I've cached the entire site as described in django docs, chaching the requests at the middleware level, using 'django.middleware.cache.UpdateCacheMiddleware' and 'django.middleware.cache.FetchFromCacheMiddleware'. I've added a link to the docs. – Martinez Mariano Jun 13 '17 at 12:16
  • clearing the cache will clear out any saved sessions. You should either use a different session backend or change the way that you cache. Do you really need to cache every single request? – Iain Shelvington Jun 13 '17 at 13:21
  • Thanks @IainShelvington, what I really need is to cache some DRF API calls, but i couldn't find an easy way to do that, because I cant use the decorator '@cache_page'. Then I cached the entire site and then excluded some pages. Which other sessions engine can I use? – Martinez Mariano Jun 13 '17 at 13:29

1 Answers1

0
from django.contrib.auth import update_session_auth_hash

update_session_auth_hash(request, user)

pass request and user in above method when you clearing a cache. but according to your way. you are clearing cache in signal that don't have request. So if you are updating Advert model from admin then. override admin save_model() method to save and here you can get user and request, So call above update_session_auth_hash after clear cache. It will not logged out user. If you updating data from own view then use same to call method that continue user as logged in.

Edit

def form_valid(self, form)
    user = self.request.user
    form.save()  # When you save then signal will call that clear your cache
    update_session_auth_hash(self.request, user)
Neeraj Kumar
  • 3,851
  • 2
  • 19
  • 41
  • The object is being created from a CreateVIew. I've overridden the method form_valid and called update_session_auth_hash(request, user) before saving the object and clearing cache, but user still being logged out. – Martinez Mariano Jun 13 '17 at 15:40