Django Sessions
What are the points we will cover in this documentation?
-
First, we will see introduction about sessions.
-
Second, we will do that sessions expires when the user closes the browser.
-
In third step we will see sessions expires after a period of inactivity
Step1: -
Intoduction: -
What are Sessions?
The session is a semi-permanent and two-way communication between the server and the browser.
Let’s understand this technical definition in detail. Here semi means that session will exist until the user logs out or closes the browser. The two-way communication means that every time the browser/client makes a request, the server receives the request and cookies containing specific parameters and a unique Session ID which the server generates to identify the user. The Session ID doesn’t change for a particular session, but the website generates it every time a new session starts.
Generally, Important Session Cookies containing these Session IDs deletes when the session ends. But this won’t have any effect on the cookies which have fix expire time.
Making and generating sessions securely can be a hefty task, and now we will look at Django’s implementation of the same.
Django Sessions
Django considers the importance of sessions over the website and therefore provides you with middleware and inbuilt app which will help you generate these session IDs without much hassle.
django.contrib.sessions is an application which works on middleware.SessionMiddleware and is convenient to work.
The middleware.SessionMiddleware is responsible for generating your unique Session IDs. You will also require django.contrib.sessions application, if you want to store your sessions on the database.
When we migrate the application, we can see the django_session table in the database.
The django.contrib.sessions application is present in the list of INSTALLED_APPS in settings.py file.
Step2: -
Sessions expire when the user closes the browser:
To work on this task, we need to add one line our ‘settings.py’ i.e.
SESSION_EXPIRE_AT_BROWSER_CLOSE
By default, the value of SESSION_EXPIRE_AT_BROWSER_CLOSE is False. So, we need to add this line into ‘setting.py’ file and set it to ‘True’.
Step3: -
Sessions expire after a period of inactivity:
To work on this task, we need to add one line our ‘settings.py’ i.e.
SESSION_COOKIE_AGE
By default, the value of SESSION_COOKIE_AGE is 1209600. So, we need to add this line into ‘setting.py’ file and set it to ‘5 * 60’(5 minutes).