How sessions work in Django?

  • The session framework stores and retrieves data.
  • It stores the data on the server side and sends and receives the cookies.
  • Cookies contain a session ID, not the data itself unless we are using the cookie-based sessions.
  • Django provides support for anonymous sessions.

Configuring the session engine:

By default, Django stores sessions in our database. We can configure Django to store session data using these sessions engines:
  1. Database-backed sessions
  2. Cached sessions
  3. File-based sessions
  4. Cookie-based sessions
Database-backed sessions:
  • To use databased-backed sessions we need to add "django.contrib.sessions" to our INSTALLED_APPS setting.
  • After this configuration, we need to run manage.py migrate to install the database table that stores session data.
Cached sessions:
  • For better performance, we can use a cached-based session backend.
  • We should only use it if we are using Memcached cache backend.
File-based sessions:
  • To use file-based sessions, set the SESSION_ENGINE setting to "django.contrib.sessions.backends.file".
  • We can set SESSION_FILE_PATH setting (which defaults to output from tempfile.gettempdir(), most likely /tmp) to control where Django stores session files.
Cookie-based sessions:
  • To use cookies-based session, set the SESSION_ENGINE setting to "django.contrib.sessions.backends.signed_cookies".
  • If we use cookie-based sessions, pay extra care that our secret key is always kept completely secret, for any system which might be remotely accessible.

Comments

Popular posts from this blog

What is composite key?

What are the different data types in Python?

What is __repr__ function?