Saturday, September 21, 2024
Google search engine
HomeLanguagesPython | Sessions framework using django

Python | Sessions framework using django

Prerequisites: Django Installation | Introduction to Django

Sessions framework can be used to provide persistent behaviour for anonymous users in the website.Sessions are the mechanism used by Django for you store and retrieve data on a per-site-visitor basis.Django uses a cookie containing a special session id.

To enable the session in the django, you will need to make sure of two things in settings.py :

  1. MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activated
  2. INSTALLED_APPS has ‘django.contrib.sessions’ added.



  3. # Application definition
    INSTALLED APPS = [
    'dhun',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    ]
    MIDDLEWARE = [
    'django.middleware.securitY.SecuritYMiddleware',
    'django.contrib.sessions.middleware.SessionMiddLeware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMidd1eware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    
    

After enabling the session, the session database table has to create and to do this run the following command:

python manage.py syncdb

After running previous command and if it didn’t find any errors then later run the command given below to finally reflect the changes saved onto the migration file onto the database.

python manage.py migrate

Now once sessions are created, then testing of the cookies has to be done. In views.py, set the test cookie in the index view, and test the cookie in your about view.




from django.shortcuts import render
from django.http import HttpResponse
from .models import Album
  
def home(request) :
    a = Album.objects.all()
    return render(request, "dhun/home.html ", {"Album":a})
      
def index(request) :
    num_authors = Author.objects.count()
    request.session.set_test_cookie()
    num_visits = request.session.get( 'num_visits', 0)
    request.session ['num_visits'] = num_visits + 1
    context ={
        'num_books':num_books,
        'num_instances':num_instances,
        'num_instances available':num_instances_available,
        'num_authors':num_authors,
        'num_visits':num_visits,
    }
          
def about(request):
    LANGUAGE_CODE ='en-us '
    TIME_ZONE ='UTC'
    if request.session.test_cookie_worked():
        print ("Cookie Tested !")
        request.session.delete_test_cookie()


To see the work done till now.

  • First run the localhost through this command.
    python manage.py runserver
  • Then Open http://localhost:8000/ in the browser.
  • Visit the index page then visit the about page. The “Cookie Tested!” will be printed out to the console.

To know how many times the site has been visited.You have to do following two things In views.py:

  1. Add and update the code in the index view function/li>
  2. Update the about view function



  3. from django.shortcuts import render
    from django.http import HttpResponse
    from .models import Album
      
    def home(request):
        a = AIbum. objects.all()
        return render(request, "dhun/home.html", {"album":a})
      
    def index(request):
        visits = int(reques.COOKIES.get('visits', '0'))
        response = HttpResponse(template.render(context))
      
        if request.COOKIES.has_key('last_visit'):
            last_visit = request. COOKIES [ ' last_visit']
            last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S") "
            curr_time = datetime.now()
            if (curr_time—last_visit_time).days > O:
                response.set_cookie( 'visits ', visits + 1)
                response. set_cookie( ' last_visit', datetime.now())
            else :
                response.set_cookie( ' last_visit', datetime.now())
            return response
      
    def about(request) :
        context = RequestContext(request)
        if request.COOKIES.has_key(' visits '):
            v = request.COOKIES [' visits ']
        else :
            v = 0
        return render_to_response('music/about.html', { 'visits':v}, context)

    
    

Reference: https://docs.djangoproject.com/en/2.1/topics/http/sessions/

RELATED ARTICLES

Most Popular

Recent Comments