How to use Django's built-in sessions framework



Image not found!!

Django provides a built-in session framework that allows you to store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. The session framework is optional and can be used to store data on a per-site-visitor basis for the duration of a user’s visit.

Here's a basic guide on how to use Django's built-in sessions framework:

  1. Enable Sessions in your Django project:

    In your settings.py file, make sure the django.contrib.sessions.middleware.SessionMiddleware is included in the MIDDLEWARE setting:

    python
    MIDDLEWARE = [ # ... 'django.contrib.sessions.middleware.SessionMiddleware', # ... ]

    Also, make sure the django.contrib.sessions app is included in your INSTALLED_APPS:

    python
    INSTALLED_APPS = [ # ... 'django.contrib.sessions', # ... ]
  2. Configure the session engine:

    In your settings.py file, you need to specify the session engine. Django provides different engines like database-backed sessions, cached sessions, or file-based sessions. Choose the one that suits your project. For example, to use the database-backed session engine:

    python
    SESSION_ENGINE = 'django.contrib.sessions.backends.db'
  3. Use sessions in your views:

    In your views, you can use the request.session dictionary to store and retrieve data for the current session. Here's a simple example:

    python
    def set_session_variable(request): # Set a session variable request.session['favorite_color'] = 'blue' return HttpResponse("Favorite color set to blue.") def get_session_variable(request): # Get a session variable favorite_color = request.session.get('favorite_color', 'default_color') return HttpResponse(f"Favorite color is {favorite_color}.")

    In the example above, the set_session_variable view sets a session variable, and the get_session_variable view retrieves it. If the session variable doesn't exist, it defaults to 'default_color'.

  4. Session expiration and cleanup:

    By default, Django uses database-backed sessions, and the session data is cleared from the database when the user's session has expired (based on the SESSION_COOKIE_AGE setting). You can customize the expiration time in your settings.py:

    python
    # Set session cookie age to 1 day (in seconds) SESSION_COOKIE_AGE = 86400

    Additionally, Django provides a management command to clean up expired sessions:

    bash
    python manage.py clearsessions

    You can run this command as a cron job to regularly clean up expired sessions from your database.

That's a basic overview of using Django's built-in sessions framework. You can find more details and options in the Django documentation: Django Sessions.