Python | Sessions framework using django

24 Jun, 2019
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 :
MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activatedINSTALLED_APPS has ‘django.contrib.sessions’ added.# Application definitionINSTALLED 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',]
MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activated
INSTALLED_APPS has ‘django.contrib.sessions’ added.
# Application definitionINSTALLED 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 renderfrom django.http import HttpResponsefrom .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
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:
Add and update the code in the index view function/li>Update the about view functionfrom django.shortcuts import renderfrom django.http import HttpResponsefrom .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)
Add and update the code in the index view function/li>
Update the about view function
from django.shortcuts import renderfrom django.http import HttpResponsefrom .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/
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON