[Answered ]-Django – set expiry for a certain key in session

2πŸ‘

From what I can recall, there is no way to expire specific keys. As a workaround, I’d suggest storing the date/time at which β€˜a’ was set or updated.

With this data you can either create a middleware, which could be fairly heavy depending on the size of the session data, or alternatively create a cron job to run at regular intervals to expire all keys where the date/time they were set/updated is outside of your threshold.

πŸ‘€Dan Ward

0πŸ‘

There is no way to give expiry time to specific session keys.

So, if setting the expiry time "60 seconds" for session with "set_expiry()" as shown below, all session keys have "60 seconds" expiry time:

request.session.set_expiry(60)

So, in this case, even for Django Admin, users can be logged in only 60 seconds. So after 60 seconds, users are taken back to the login page as shown below:

enter image description here

In addition, as a test, I set "120 and 60 seconds" expiry time to two specific session keys "test1" and "test2" respectively as shown below but for both "test1" and "test2" session keys, "60 seconds" is prioritized instead of "120 seconds":

# "views.py"

def test(request):

    request.session.set_expiry(120) # Not Prioritized
    request.session['test1'] = 'test1'
    
    request.session.set_expiry(60) # Prioritized
    request.session['test2'] = 'test2'

    return render(request, 'test/index.html')

This is the session id for all session keys as shown below:

enter image description here

Leave a comment