How to expire session due to inactivity in Django?

后端 未结 6 1622
一整个雨季
一整个雨季 2020-11-28 00:52

Our Django application has the following session management requirements.

  1. Sessions expire when the user closes the browser.
  2. Sessions expire after a pe
6条回答
  •  情歌与酒
    2020-11-28 01:30

    Here's an idea... Expire the session on browser close with the SESSION_EXPIRE_AT_BROWSER_CLOSE setting. Then set a timestamp in the session on every request like so.

    request.session['last_activity'] = datetime.now()
    

    and add a middleware to detect if the session is expired. something like this should handle the whole process...

    from datetime import datetime
    from django.http import HttpResponseRedirect
    
    class SessionExpiredMiddleware:
        def process_request(request):
            last_activity = request.session['last_activity']
            now = datetime.now()
    
            if (now - last_activity).minutes > 10:
                # Do logout / expire session
                # and then...
                return HttpResponseRedirect("LOGIN_PAGE_URL")
    
            if not request.is_ajax():
                # don't set this for ajax requests or else your
                # expired session checks will keep the session from
                # expiring :)
                request.session['last_activity'] = now
    

    Then you just have to make some urls and views to return relevant data to the ajax calls regarding the session expiry.

    when the user opts to "renew" the session, so to speak, all you have to do is set requeset.session['last_activity'] to the current time again

    Obviously this code is only a start... but it should get you on the right path

提交回复
热议问题