Manage sessions in Django

Tram Ho

When we use sessions, data is not stored directly in the browser. Instead they are stored at the server. Django creates a random string of 32 characters called the session key and associates it with the session data. The server then sends a cookie called sessionid, containing the session key, with the value to the browser. In subsequent requests, the browser sends a session cookie to the server. Django then uses this cookie to retrieve session data and make it accessible in your code.

1. Config session

In order to setup using session in Django, we need to add it in the file

  • ‘django.contrib.sessions.middleware.SessionMiddleware’to MIDDLEWARE
  • ‘django.contrib.sessions’ to INSTALLED_APPS. Run python migrate to initialize the tables. A 3-column django_session table will be generated: session_key, session_data, and expire_date.

These settings will be added automatically when creating a new project

2. Test your browser’s cookie capabilities

We know users can customize their browser to not allow any cookies. Django provides several convenient methods to check whether cookies serve your browser. Object request.sessions provides three methods tracking to check browser support cookies.

  • set_test_cookie (): Set a test cookie to determine if a user’s browser supports cookies. Due to the way cookies work, you can check this until the user requests the next page.
  • test_cookie_worked (): Returns True or False, depending on whether the user’s browser allows cookies to be tested. Due to the way cookies work, you will have to call set_test_cookie () in the previous separate page request.
  • delete_test_cookie (): Delete test cookies.

When the browser is in use, it checks whether cookies are allowed. Otherwise it will send a test cookie and show error message to allow.

3. Read and write session data

A Django request has a session attribute that acts like a dictionary

  • set session data

  • read session data

  • delete session data

4. SessionMiddleware role

Let’s check the code ‘django.contrib.sessions.middleware.SessionMiddleware’ to understand

  • Middewares are called before and after the views are called, process_request (self, request) is used first and process_response (self, request, response) is used after the view call
  • process_request: check if there is a cookie with the sessionid name (default value of settings.SESSION_COOKIE_NAME) in request.COOKIES. If found, it will attempt the session to use the session_key column in the session database
  • process_response checks whenever request.session is edited or created. It then creates or stores the session data in the session database and adds a sessionid cookie to return with session_key and value.If it finds the request.COOKIES is not empty and all session data is deleted, after the session is removed from the database. and delete session cookie from response, cookie in browser is also deleted

With the save_session_data () function when called

  • ‘django.contrib.sessions.middleware.SessionMiddleware’ middleware creates any key session and links to the session data
  • ‘django.contrib.sessions.middleware.SessionMiddleware’ uses the ‘django.contrib.sessions’ to store a session in the database
  • A cookie with sessionid name with any value generated from step 1 is sent to the browser
  • From then on, the browser will send the sessionid with each request to the server, allowing Python code to access the session data data in views using request.session.

When access_session_data is called after save_session_data, the sessionid cookie is available in the request.COOKIES, the process_request of the middleware uses the sessionid to store the session in the request.

At delete_session_data, we will delete session_data, middleware will determine that there will be no session, it will be deleted in the response and cookies in the browser.

5. When sessions are saved

By default, Django only stores sessions in the database when the session is modified, if any value is assigned or deleted

Another important point worth mentioning is that Django only sends session cookies to the browser when the session data is modified. In the process, it also updates the cookie expiry time.

  • session_key: store any unique session id
  • session_data; Django stores encrypted session data, to retrieve data using get_decode ()
  • expire_date: duration of session cookie

Source: ?

Share the news now

Source : Viblo