In django, how is request.session.set_expiry used to log out users after idle?

Question:

I want to log users out after some period of inactivity. This question (Logging users out of a Django site after N minutes of inactivity) has a reasonable looking answer.

But I’d like to understand what distinguishes request.session.set_expiry from SESSION_COOKIE_AGE. The former seems to log the user out after a fixed period regardless of activity. Isn’t this also what SESSION_COOKIE_AGE does if SESSION_SAVE_EVERY_REQUEST is False?

Asked By: Mitch

||

Answers:

From what I can tell, request.session.set_expiry simply overrides the SESSION_COOKIE_AGE setting for that specific session. With SESSION_SAVE_EVERY_REQUEST = False (the default), there would be no functional difference.

In both cases, session activity is based off of when the session was last modified (unless SESSION_SAVE_EVERY_REQUEST is True, in which case it is saved on every request, so it’s effectively modified on every request)

One example is that you may want users in a certain section of your application to have a longer session expiration, so you could use request.session.set_expiry with a custom value in the views related to that application, and then reset it with request.session.set_expiry(SESSION_COOKIE_AGE) when they leave that particular section.

Answered By: Alex Vidal

set_expiry() overrides SESSION_COOKIE_AGE. In other words, if set_expiry() is executed, set_expiry() is prioritized rather than SESSION_COOKIE_AGE.

If SESSION_SAVE_EVERY_REQUEST is "True", users are logged out if inactive.

If SESSION_SAVE_EVERY_REQUEST is "False", users are logged out whether active or inactive.

Answered By: Kai – Kazuya Ito