+

Python | Session framework using django

The session framework can be used to provide persistent behavior for anonymous users on a website. Sessions — it is the mechanism Django uses to store and retrieve data for each site visitor. Django uses a cookie that contains a special session identifier.

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

  1. MIDDLEWARE_CLASSES has django.contrib.sessions.middleware.SessionMiddleware enabled
  2. INSTALLED_APPS added & # 39; django.contrib.sessions & # 39;.

    # 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 .c ontrib.messages.middleware.MessageMiddleware` ,

    `django.middleware.clickjacking.XFrameOptionsMiddleware` ,

    ]

After enabling the session, the session database table must be created and to do this run the following command:

 python manage.py syncdb  

After running the previous command and if it doesn`t find any errors, then run the command below to finally reflect the changes saved in the migration file in the database.

 python manage .py migrate 

Now that the sessions are created, you need to test your cookies. In views.py , set a 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 so far.

  • First start localhost with this command.
     python manage.py runserver 
  • Then open http:// localhost: 8000 / in your browser.
  • Visit the index page, then go to the about page. "Cookie Tested!" Will be printed to the console.
       

To see how many times a site has been visited. There are two things you need to do in views.py:

  1. Add and update the code in the index viewer.
  2. Update the viewer
  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 & gt; 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)

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

Get Solution for free from DataCamp guru