From django's documentation, I became under the impression that calling:
request.session.set_expiry(300)
from one view would cause the session to expire after five minutes inactivity; however, this is not the behavior that I'm experiencing in django trunk. If I call this method from one view, and browse around to other views that don't call the method, the session expires in five minutes. The behavior that I was expecting was a expire only after five minutes of inactivity and not simply failing to call set_expiry again before the expiry.
My question then is do I really need to call set_expiry in every view? If so, does there exist some decorator that may be of assistance? I can't imagine this isn't part of contrib.
Thanks, Pete
Add timestamp to sessions to expire them independently.
Set the expiry date of the session to be 'current time + inactivity period' on every request. Override process_request in SessionMiddleware and check for session expiry. Discard the session if it has expired.
To delete a session or any particular key of that session, we can use del. The output will look like this and don't worry if your cookie didn't delete because we use this method only to delete your data in the Django database and not the session ID and cookie itself.
As the author of those methods, I can see that the documentation isn't very clear regarding this. Your observations are correct: only requests which cause the session to be altered is considered "activity".
You can use the SESSION_SAVE_EVERY_REQUEST
setting to get the behavior you're after (at the obvious cost of the session having to being saved every request).
Note : It will update the existing session record with latest expiry date.
A simple middleware would probably do better than setting this up in every view. This is what I used.
class SessionExpiry(object):
""" Set the session expiry according to settings """
def process_request(self, request):
if getattr(settings, 'SESSION_EXPIRY', None):
request.session.set_expiry(settings.SESSION_EXPIRY)
return None
This depends on SESSION_EXPIRY
being set in your config. It's format is the same as request.session.set_expiry
.
MIDDLEWARE_CLASSES
should be defined with this order in mind:
MIDDLEWARE_CLASSES = (
...
'django.contrib.sessions.middleware.SessionMiddleware',
'<yourproject>.<yourapp>.middleware.SessionExpiry',
...
}
It'd be nice if django.contrib.sessions
took this setting into account by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With