How to check how much session expiry time is left? (Django)

Viewed 54

With "views.py" as shown below, I'm trying to check how much session expiry time is left by setting "60" seconds expiry time but after "20" seconds sleep, get_expiry_age(), get_session_cookie_age() and get_expiry_date() didn't return "40" seconds expiry time which is expected:

# "views.py"

from django.shortcuts import render
import time

def test(request):
    request.session.set_expiry(60) # "60" seconds expiry time is set

    time.sleep(20) # Sleep for "20" seconds

    print(request.session.get_expiry_age())         # 60
    print(request.session.get_session_cookie_age()) # 1209600 
    print(request.session.get_expiry_date())        # 2022-08-07 00:34:41.700828+00:00
    
    return render(request, 'test/index.html')

So, are there any ways to check how much session expiry time is left?

1 Answers

I think while it is in your view expiry_age of original request won't get updated and It will get Updated after your response passes the process_response in SessionMiddleware. If you check the source code you see this in set_expiry it sets the value in self['_session_expiry'] = value.

def set_expiry(self, value):
    """
    Set a custom expiration for the session. ``value`` can be an integer,
    a Python ``datetime`` or ``timedelta`` object or ``None``.

    If ``value`` is an integer, the session will expire after that many
    seconds of inactivity. If set to ``0`` then the session will expire on
    browser close.

    If ``value`` is a ``datetime`` or ``timedelta`` object, the session
    will expire at that specific future time.

    If ``value`` is ``None``, the session uses the global session expiry
    policy.
    """
    if value is None:
        # Remove any custom expiration for this session.
        try:
            del self['_session_expiry']
        except KeyError:
            pass
        return
    if isinstance(value, timedelta):
        value = timezone.now() + value
    self['_session_expiry'] = value

and then in get_expiry_age is uses the same key if it exist to show you expiry age.

def get_expiry_age(self, **kwargs):
    """Get the number of seconds until the session expires.

    Optionally, this function accepts `modification` and `expiry` keyword
    arguments specifying the modification and expiry of the session.
    """
    try:
        modification = kwargs['modification']
    except KeyError:
        modification = timezone.now()
    # Make the difference between "expiry=None passed in kwargs" and
    # "expiry not passed in kwargs", in order to guarantee not to trigger
    # self.load() when expiry is provided.
    try:
        expiry = kwargs['expiry']
    except KeyError:
        expiry = self.get('_session_expiry')

    if not expiry:   # Checks both None and 0 cases
        return self.get_session_cookie_age()
    if not isinstance(expiry, datetime):
        return expiry
    delta = expiry - modification
    return delta.days * 86400 + delta.seconds

if you set the expiry in a view and return a response the new expiry age will be visible in all the requests after that but you can't use it in the same view before your SessionMiddleware has processed it.

Related