Removing sessions from Redis (Django)

I'm using Django and Redis as my session mechanism (also Celery, but that's something else). It works great and I see an improvement in speed.

SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

      

I have a script that runs every minute to check for active users using some methods, and if the user was not active at the last minute, the session is deleted. This is for customer tracking needs.

This script worked fine until I switched to Redis as my session engine. The session is indeed removed from the DB, but not from Redis. I'm not using Django's built-in method, but my own function:

def clean_sessions():
    stored_sessions = Session.objects.all()
    active_users = active_users(minutes=1)
    active_users_ids = [user.id for user in active_users]
    for session in stored_sessions:
        session_uid = session.get_decoded().get('_auth_user_id')
        if not session_uid:
            session.delete()
            continue
        if session_uid not in active_users_ids:
            user = User.objects.get(pk=session_uid)
            ## some code between ##
            session.delete()

      

My question is, how do I delete the session from the cache so that the user is actually logged out?

+3


source to share


1 answer


It wasn't very easy, but I was able to fix it. I imported this from a file, I have my clean_sessions ():

from importlib import import_module
from django.conf import settings

      

Then, inside the function, I loaded the SessionStore object:

SessionStore = import_module(settings.SESSION_ENGINE).SessionStore

      



From there, it was very easy to delete sessions, leaving the method like this:

def clean_sessions():
    stored_sessions = Session.objects.all()
    active_users = Request.objects.active_users(seconds=15)
    active_users_ids = [user.id for user in active_users]
    for session in stored_sessions:
        SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
        s = SessionStore(session_key=session.session_key)
        session_uid = session.get_decoded().get('_auth_user_id')
        if not session_uid:
            s.delete()
            continue
        if session_uid not in active_users_ids:
            ## some code ##
            s.delete()

      

It is very important to load the correct SessionStore from whatever session engine is in use, otherwise it will not be able to remove it from both locations (DB and cache).

+1


source







All Articles