How to expire session due to inactivity in Django?

| | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Our Django application has the following session management requirements.

  1. Sessions expire when the user closes the browser.
  2. Sessions expire after a period of inactivity.
  3. Detect when a session expires due to inactivity and display appropriate message to the user.
  4. Warn users of a impending session expiry a few minutes before the end of the inactivity period. Along with the warning, provide users an option to extend their session.
  5. If user is working on a long business activity within the app that doesn"t involve requests being sent to the server, the session must not timeout.

After reading the documentation, Django code and some blog posts related to this, I have come up with the following implementation approach.

Requirement 1
This requirement is easily implemented by setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True.

Requirement 2
I have seen a few recommendations to use SESSION_COOKIE_AGE to set the session expiry period. But this method has the following problems.

  • The session always expires at the end of the SESSION_COOKIE_AGE even if the user is actively using the application. (This can be prevented by setting the session expiry to SESSION_COOKIE_AGE on every request using a custom middleware or by saving the session on every request by setting SESSION_SAVE_EVERY_REQUEST to true. But the next problem is unavoidable due to the use of SESSION_COOKIE_AGE.)

  • Due to the way cookies work, SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE are mutually exclusive i.e. the cookie either expires on browser close or at the specified expiry time. If SESSION_COOKIE_AGE is used and the user closes the browser before the cookie expires, the cookie is retained and reopening the browser will allow the user (or anyone else) into the system without being re-authenticated.

  • Django relies only on the cookie being present to determine if the session is active. It doesn"t check the session expiry date stored with the session.

The following method could be used to implemented this requirement and to workaround the problems mentioned above.

  • Do not set SESSION_COOKIE_AGE.
  • 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.

Requirement 3
When we detect that the session has expired (in the custom SessionMiddleware above), set an attribute on the request to indicate session expiry. This attribute can be used to display an appropriate message to the user.

Requirement 4
Use JavaScript to detect user inactivity, provide the warning and also an option to extend the session. If the user wishes to extend, send a keep alive pulse to the server to extend the session.

Requirement 5
Use JavaScript to detect user activity (during the long business operation) and send keep alive pulses to the server to prevent session from expiring.


The above implementation approach seem very elaborate and I was wondering if there might a simpler method (especially for Requirement 2).

Any insights will be highly appreciated.

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from How to expire session due to inactivity in Django?, check other code Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Carlo Porretti

Vigrinia | 2023-04-01

os Python module is always a bit confusing 😭 How to expire session due to inactivity in Django? is not the only problem I encountered. Checked yesterday, it works!

Chen Innsbruck

Berlin | 2023-04-01

Event PHP module is always a bit confusing 😭 How to expire session due to inactivity in Django? is not the only problem I encountered. I am just not quite sure it is the best method

Anna Wu

Shanghai | 2023-04-01

I was preparing for my coding interview, thanks for clarifying this - How to expire session due to inactivity in Django? in Python is not the simplest one. I am just not quite sure it is the best method

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically