Bird
Raised Fist0
Djangoframework~5 mins

Session expiry behavior in Django

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

Sessions help remember who a user is while they browse your site. Session expiry makes sure this memory doesn't last forever, keeping things safe and tidy.

You want users to log in again after some time for security.
You want to clear user data after they close the browser.
You want to limit how long a user stays logged in without activity.
You want to control session length for different parts of your site.
Syntax
Django
SESSION_COOKIE_AGE = 1209600  # Time in seconds (default 2 weeks)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

# To set session expiry in a view:
request.session.set_expiry(value)

# value can be:
# - an integer (seconds)
# - 0 (expire on browser close)
# - None (use global settings)

SESSION_COOKIE_AGE sets how long sessions last by default.

SESSION_EXPIRE_AT_BROWSER_CLOSE makes sessions end when the browser closes if set to True.

Examples
This sets all sessions to expire after 1 hour.
Django
SESSION_COOKIE_AGE = 3600  # Sessions last 1 hour
Sessions will end when the user closes their browser.
Django
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
This view sets the session to expire 5 minutes after the last activity.
Django
def my_view(request):
    request.session.set_expiry(300)  # expire after 5 minutes
    return HttpResponse('Session set to 5 minutes')
This makes the session end when the browser closes, overriding global settings.
Django
def my_view(request):
    request.session.set_expiry(0)  # expire on browser close
    return HttpResponse('Session expires on browser close')
Sample Program

This example has two views. One sets a session that expires in 10 seconds and stores a user name. The other checks if the session still has the user.

Django
from django.http import HttpResponse

def set_short_session(request):
    # Set session to expire after 10 seconds
    request.session.set_expiry(10)
    request.session['user'] = 'Alice'
    return HttpResponse('Session set for 10 seconds')

def check_session(request):
    user = request.session.get('user', 'No session')
    return HttpResponse(f'User in session: {user}')
OutputSuccess
Important Notes

Session expiry counts from the last user activity, so it resets if the user keeps interacting.

Setting expiry to 0 means the session ends when the browser closes, which is good for sensitive data.

Always test session expiry behavior in your browser's private mode to avoid cached sessions.

Summary

Sessions remember users but should not last forever for safety.

You can control session length globally or per user with set_expiry().

Use session expiry to improve security and user experience.

Practice

(1/5)
1. What does the set_expiry() method do in Django sessions?
easy
A. It encrypts the session data.
B. It deletes the session immediately.
C. It sets how long a user's session will last before expiring.
D. It creates a new session key for the user.

Solution

  1. Step 1: Understand the purpose of set_expiry()

    This method controls the lifetime of a session by setting its expiration time.
  2. Step 2: Compare options with the method's function

    Only It sets how long a user's session will last before expiring. correctly describes that set_expiry() sets how long the session lasts before it expires.
  3. Final Answer:

    It sets how long a user's session will last before expiring. -> Option C
  4. Quick Check:

    Session expiry time = set_expiry() [OK]
Hint: Remember: set_expiry controls session lifetime [OK]
Common Mistakes:
  • Confusing set_expiry() with session deletion
  • Thinking it creates or encrypts sessions
  • Assuming it resets session data
2. Which of the following is the correct way to set a session to expire in 300 seconds in Django?
easy
A. request.session.expire(300)
B. request.session.set_expiry(300)
C. request.set_expiry(300)
D. session.set_expiry_time(300)

Solution

  1. Step 1: Identify the correct method and object

    The method set_expiry() is called on request.session to set expiry time.
  2. Step 2: Check syntax correctness

    request.session.set_expiry(300) uses the correct method and object: request.session.set_expiry(300). Other options use incorrect method names or objects.
  3. Final Answer:

    request.session.set_expiry(300) -> Option B
  4. Quick Check:

    Correct method call = request.session.set_expiry(300) [OK]
Hint: Call set_expiry on request.session, not request [OK]
Common Mistakes:
  • Calling set_expiry on request instead of request.session
  • Using wrong method names like expire or set_expiry_time
  • Missing parentheses or wrong argument
3. Given this code snippet, what will be the session expiry behavior?
request.session.set_expiry(0)
medium
A. The session expiry will use the default global timeout.
B. The session will never expire.
C. The session will expire after 0 seconds immediately.
D. The session will expire when the browser is closed.

Solution

  1. Step 1: Understand what passing 0 to set_expiry means

    In Django, setting expiry to 0 means the session expires when the browser closes (a browser-length session).
  2. Step 2: Compare with other options

    The session will expire when the browser is closed. matches this behavior. The session will never expire. is false because 0 does not mean never expire. The session will expire after 0 seconds immediately. is incorrect because it does not expire immediately. The session expiry will use the default global timeout. is incorrect because default timeout is overridden.
  3. Final Answer:

    The session will expire when the browser is closed. -> Option D
  4. Quick Check:

    set_expiry(0) = expire on browser close [OK]
Hint: 0 means expire on browser close, not immediately [OK]
Common Mistakes:
  • Thinking 0 means no expiry
  • Assuming immediate expiry at 0 seconds
  • Confusing with default session timeout
4. What is wrong with this code snippet if the goal is to set the session to expire after 10 minutes?
request.session.set_expiry = 600
medium
A. It assigns a value to the method instead of calling it.
B. The expiry time should be in milliseconds, not seconds.
C. The session object does not have set_expiry attribute.
D. The value 600 is too large and causes an error.

Solution

  1. Step 1: Analyze the code syntax

    The code assigns 600 to set_expiry instead of calling it as a method with parentheses.
  2. Step 2: Understand correct usage

    The correct usage is request.session.set_expiry(600) to call the method and set expiry time.
  3. Final Answer:

    It assigns a value to the method instead of calling it. -> Option A
  4. Quick Check:

    Use parentheses to call set_expiry() [OK]
Hint: Use parentheses to call set_expiry(), not assignment [OK]
Common Mistakes:
  • Assigning value instead of calling method
  • Confusing seconds with milliseconds
  • Believing 600 causes error due to size
5. You want a session to expire after 5 minutes but also want to keep the session alive if the user is active. Which approach correctly achieves this in Django?
hard
A. Set set_expiry(300) on every user request to reset expiry time.
B. Set set_expiry(300) once when the session is created only.
C. Set set_expiry(0) to expire on browser close and ignore activity.
D. Do not set expiry; rely on default session timeout.

Solution

  1. Step 1: Understand session expiry reset behavior

    Calling set_expiry(300) on every request resets the expiry countdown, keeping session alive if user is active.
  2. Step 2: Evaluate other options

    Set set_expiry(300) once when the session is created only. sets expiry once, so session expires after 5 minutes regardless of activity. Set set_expiry(0) to expire on browser close and ignore activity. expires on browser close, ignoring time. Do not set expiry; rely on default session timeout. uses default timeout, no control.
  3. Final Answer:

    Set set_expiry(300) on every user request to reset expiry time. -> Option A
  4. Quick Check:

    Reset expiry on each request = Set set_expiry(300) on every user request to reset expiry time. [OK]
Hint: Reset expiry timer on each request to keep session alive [OK]
Common Mistakes:
  • Setting expiry only once at session creation
  • Using 0 expiry which ignores time
  • Relying on default timeout without control