session.get_expiry_age() never decreases

Question:

I set SESSION_COOKIE_AGE to some value in my settings.py and I want to retrieve the time that is left before a session dies by using session.get_expiry_age() from a view.

However, it seems the returned value is never changing between different calls (at different times): it stays at SESSION_COOKIE_AGE, meaning the session will never end(?)

Is it a normal behaviour? I would like to notify the user whenever the session is about expire and I don’t really see how to do it.

Asked By: Buddyshot

||

Answers:

Yes, this is the intended behaviour. See this ticket: https://code.djangoproject.com/ticket/18458

You can use get_expiry_date() instead and calculate it from there.

Answered By: Tom Carrick

I tried to find the way to get how much session expiry time is left.

Then, I tested get_expiry_age(), get_session_cookie_age() and get_expiry_date() with "time.sleep(60)" in "test" view as shown below. Then, without counting down(decreasing) session expiry time, get_expiry_age() always returns the value of SESSION_COOKIE_AGE or set_expiry() and get_session_cookie_age() always returns the value of SESSION_COOKIE_AGE and get_expiry_date() returns the session expiry date from the current date as shown below:

from django.shortcuts import render
import time

def test(request):
    print(request.session.get_expiry_age())         # 1209600
    print(request.session.get_session_cookie_age()) # 1209600
    print(request.session.get_expiry_date())        # 2022-08-19 22:19:05.376943+00:00
    
    time.sleep(60)

    print(request.session.get_expiry_age())         # 1209600
    print(request.session.get_session_cookie_age()) # 1209600
    print(request.session.get_expiry_date())        # 2022-08-19 22:20:05.392306+00:00
    
    return render(request, 'test/index.html')

Finally, I couldn’t find the way to get how much session expiry time is left.

Answered By: Kai – Kazuya Ito