Quick Contact

    Python Tutorial
    Python Panda Tutorial
    Python Selenium
    Python Flask Tutorial
    Python Django
    Numpy
    Tensorflow
    Interview Questions & Answers

    Django Sessions

    As we know, HTTP is a stateless protocol, where every request made is always new to the server. The request on the server is always treated as if the user is visiting the site for the first time. This poses some problems like you can’t implement user login and authentication features. These problems were actually solved by Cookies.

    What are Cookies?

    Cookies are small text files stored and maintained by the browser. It contains some information about the user and every time a request is made to the same server, the cookie is sent to the server so that the server can detect that the user has visited the site before or is a logged in user.

    The cookies also have their drawbacks and a lot of times they become a path for the hackers and malicious websites to damage the target site.

    Drawbacks of Cookies

    Since cookies store locally, the browser gives control to the user to accept or decline cookies. Many websites also provide a prompt to users regarding the same.

    Cookies are plain text files, and those cookies which are not sent over HTTPS can be easily caught by attackers. Therefore, it can be dangerous for both the site and the user to store essential data in cookies and returning the same again and again in plain text.

    These are some of the more common problems that web developers were facing regarding cookies.

    What are Sessions?

    After observing these problems of cookies, the web-developers came with a new and more secure concept, Sessions.

    The session is a semi-permanent and two-way communication between the server and the browser.

    Let’s understand this technical definition in detail. Here semi means that session will exist until the user logs out or closes the browser. The two-way communication means that every time the browser/client makes a request, the server receives the request and cookies containing specific parameters and a unique Session ID which the server generates to identify the user.

    The Session ID doesn’t change for a particular session, but the website generates it every time a new session starts.

    Generally, Important Session Cookies containing these Session IDs deletes when the session ends. But, this won’t have any effect on the cookies which have fix expire time.

    Making and generating sessions securely can be a hefty task, and now we will look at Django’s implementation of the same.

    Django Sessions

    Django considers the importance of sessions over the website and therefore provides you with middleware and inbuilt app which will help you generate these session IDs without much hassle.

    Checking Cookies on Browser

    For adding view functions in our views.py file, enter:

    Code:

    defcookie_session(request):
    request.session.set_test_cookie()
    returnHttpResponse("< h1>ducatindia< /h1>")
    defcookie_delete(request):
    ifrequest.session.test_cookie_worked():
    request.session.delete_test_cookie()
    response = HttpResponse("ducatindia< br> cookie createed")
    else:
    response = HttpResponse("ducatindia< br> Your browser doesnot accept cookies")
    return response
    

    Now, we will understand the methods used in the above code:

    set_test_cookie()

    We use this method to create a test cookie when your browser requests or makes a request for this webpage.

    test_cookie_worked()

    This method returns a boolean value as True after the browser accepts the cookie. Otherwise, it’s false

    delete_test_cookie()

    This method deletes the test cookie.

    Now, add the urls to urlpatterns.

    Code:

    path(‘testcookie/’, cookie_session),

    path(‘deletecookie/’, cookie_delete),

    Creating & Accessing Django Sessions

    Django allows you to easily create session variables and manipulate them accordingly.

    The request object in Django has a session attribute, which creates, access and edits the session variables. This attribute acts like a dictionary, i.e., you can define the session names as keys and their value as values.

    Step 1.

    We will start by editing our views.py file. Add this section of code.

    Code:

    defcreate_session(request):
    request.session['name'] = 'username'
    request.session['password'] = 'password123'
    returnHttpResponse("< h1>dataflair< br> the session is set< /h1>")
    defaccess_session(request):
    response = "< h1>Welcome to Sessions of ducatindia< /h1>< br>"
    ifrequest.session.get('name'):
    response += "Name : {0} < br>".format(request.session.get('name'))
    ifrequest.session.get('password'):
    response += "Password : {0} < br>".format(request.session.get('password'))
    returnHttpResponse(response)
    else:
    returnredirect('create/')
    

    Step 2.

    Add the urls in urlpatterns list.

    Code:

    path(‘create/’, create_session),

    path(‘access’, access_session),

    Step 3.

    Now run this code:

    Deleting Django Sessions

    After completing the sessions work, you can delete them quite easily.

    Just include this view function inside views.py file.

    Code:

    defdelete_session(request):
    try:
    delrequest.session['name']
    delrequest.session['password']
    exceptforKeyError:
    pass
    returnHttpResponse("< h1>dataflair< br>Session Data cleared< /h1>")
    

    To delete a session or any particular key of that session, we can use del.

    delrequest.session[‘key_name’]

    Now, to run this code add this to the urlpatterns:

    path(‘delete/’, delete_session)

    Configuring Session Engine

    There are many ways by which you can configure sessions engine. It is an important decision where storage options can provide you better speed and response time.

    Django lets you choose between these options but doesn’t limit your choices. If you want another storage method, you can find it on djangopackages.org

    1. By Database-backed Sessions

      We have used this method until now, as we have django.contrib.sessions application inside our INSTALLED_APPS list in settings.py file.

      This is standard implementation and covers many security loopholes. It also provides you with lots of features to use them directly with view functions and models in Django framework.

    2. By Cached Sessions

      If you want to improve the performance of the website, you can use cache-based sessions. There are several practices which you can perform here, like setting up multiple caches.

      For this purpose, Django provides you with more session engines:

      django.contrib.sessions.backends.cache

      Above engine stores data directly into the cache.

      django.contrib.sessions.backends.cache_db

      This engine, on the other hand, is used when you want persistent sessions data with your server using write-through cache. It means that everything written to the cache will also be written to the database.

      Both methods improve your performance drastically, but the first one is faster than the second one.

    3. By File-based Sessions

      When you want to store your sessions data in a file-based system, then you can use this engine that Django provides.

      django.contrib.sessions.backends.file

      You will also need to check whether your web server has permission to read/ write the directory in which you are keeping your sessions file.

    4. By Cookie-based Sessions

      We don’t recommend this one as sessions were made for not storing data in cookies in the first place, but still, developers use it according to their need.

      django.contrib,sessions.backends.signed_cookies

      This allows your session data to store with the help of Django’s cryptographic signing tool and the secret key.

      It poses all the problems of cookies, the major one is that the session_cookies are signed but not encrypted; therefore they can be read by the client.

      Also, it has performance issues as the cookie size does affect the request size.

     

    Apply now for Advanced Python Training Course

    Copyright 1999- Ducat Creative, All rights reserved.

    Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.