1.

What is the use of the session framework in Django?

Answer»

Django SUPPORTS anonymous sessions. The Session framework allows you to store and retrieve arbitrary data on per site visitor basis. Django stores data on server-side and retrieves it by sending and receiving cookies. These cookies contain session IDs.

Enabling sessions -

Using a PIECE of middleware, sessions are implemented.

To enable session -

Open and update the MIDDLEWARE setting as below.

'django.contrib.sessions.middleware.SessionMiddleware'

Default settings.py has SessionMiddleware activated.

You can remove SessionMiddleware line from MIDDLEWARE_CLASSES and 'django.contrib.sessions' from your INSTALLED_APPS if you don't want to use sessions.

Configuring session engine

Django store sessions in the DATABASE by default. Django can be configured to store session data in two ways.

1. Using database-backed sessions - You need to add 'django.contrib.sessions' to INSTALLED_APPS settings if you want to use database-backed sessions.
    Run manage.py syncdb to install a SINGLE database table to store session data.

2. Using cached sessions - For better performance, cache-based session backend can be used. To store session data you need to configure the cache. You can store data in two ways -

  • Set SESSION_ENGINE to "django.contrib.sessions.backends.cache" for SIMPLE caching. Data will be stored directly cache. Session data may not be persistent. If the cache fills up or cache server restarted, cache data can be evicted.
  • Set SESSION_ENGINE to "django.contrib.sessions.backends.cached_db". Every write to the cache will be written to database.


Discussion

No Comment Found