Search code examples
djangodjango-sessions

Expiring specific session variable in Django


It's easy to expire the request.session dictionary via request.session.set_expiry(seconds_until_end_of_day) or via SESSION_COOKIE_AGE.

But how do I set the expiry of a specific session variable? E.g. I've alloted an unauth user a temp_id. I need this temp_id to cease to exist in 30 mins. What's the best, most performant way to achieve that?


Solution

  • How about putting it in the cache instead

    from django.core.cache import cache
    cache.set('{0}_temp_id'.format(request.session.session_key, value, timeout
    

    This is uniquely associated with the user and automatically expires. No need for complicated middleware