Django session key based expiration

Question:

I’m using Django sessions and I want to set expiry for a particular key. In an AJAX view I’m doing the following

request.session['a'] = True
request.session.set_expiry(604800)

Does this set the expiry for that particular key or that session? I’m setting the sessions for other keys in other AJAX views in a similar way.

If I print request.session.get_expiry_date() in my view I get the date 7 days from now regardless of when I set the expiry. Why would that be?

Asked By: Yin Yang

||

Answers:

As the set_expiry is a method of the session it sets the expiry of the session.

The Django session is a whole object, it is not possible (without manual work) to set the expiry for a specific key)

Answered By: Wolph

That’s because when you set_expiry as an integer the expiry age is defined as seconds of inactivity.

When you call the get_expiry_age method, a modification parameter defaults to now and the "seconds of inactivity" starts counting from zero.

If you do not want the counter to reset each time you call the get_expiry_age, you should specify a timedelta upon setting expiry:

from datetime import timedelta

request.session.set_expiry(timedelta(seconds=604800))

See what does get_expiry_age() return in Django

Answered By: ItaiG