Django

Introduction To Cookies and Session in django

blog image

Introduction to django cookies ans session

session framework on django:

The session framework lets you store and retrive arbitrary data on a per-site-visitor basis.

it store data on the side and abstracts the sending and receiving of cookies. cookies contain a session id not the data itself.

By default , django store sessions in your database. as it store sessions in db so it is mendatory to run make migrationss and migrate to use session. it will create required tables.

The django session framework is entirely and solely cookie-based.

There are many ways to store the session among then some are as follow

1.database-backed sessions:

If you want to use db-backed session,you need to add "django-contrib.sessions' to your INSTALLED_APPS setting. One you have configured your installation,run manage.py migrate to install the single db table that store session data.

2.file-based session

To use file based sessions,set the SESSION_ENGINE  setting to "django.contrib.sessions.backendsfile". you might also want to set the SESSION_FILE_PATH setting, (which defaults to output from gettempdir(). most likelt /temp) to contrib where Django stores session files. Be save to check that your web server has permissions to read and write to this location.

3.Cookie-based session

To used cookie-based session , set the SESSION_ENGINE setting to "django.ontrib.sessions.backeds.signed-cookies". The session data will be stored using Django's tools for Cryptographic signing and the SECRET_KEY setting.

4.Cached sessions.

For better performance, you want to use a cache-based session backend. to store session data using Django's cache system. you ewill need to make sure you've configured your cache.

 

How to use session in views.

When sessionsmiddleware is activated,each HttpEwquest object, the first argument to any django view function will have a session attribute, which is a dictionary-like objeect.

you can read it and write to request. session at any point in your view. you can also edit it multiple times.

set item :      request.session["key"]="value"

get item :      requested_value=request.session["key"]

                      requested_value=request.session.get("key",default=None)

delete item : del request.session["key"]

                      note: this raise keyerror if the given key isn't already in the session. firstly you need to check wheether it is contain or not                        like "key" in request.session. 

 

from django.shortcuts import render,HttpResponse

# Create your views here.
def set_session(request):
    request.session['name']="amrit panta"
    return HttpResponse("set successfully")
def get_session(request):
    data=request.session['name']
    return HttpResponse(f"data is {data}")
def delete_session(request):
    if 'name' in request.session:
        del request.session['name']
        return HttpResponse("deleted successfully")    
    return HttpResponse("session doesnot exist")

Session methos:

1.keys() -> meethod returns a view object that display a list of all keys in the dictionary. syntax: dict.keys()

2.items() -> method returns list with all dictionary keys with values. syntax: dict.items()

3.clear() -> function is used to erase all the eelements of the lst. after this operation, list becomes empty. syntax: dict.clear()

4.setdefault() -> method returns the value of a key. (if there is in dictionary) if not , it inserts key with a value to the dictionary)

5.flush() -> it deletes the current session data from the session and dekete the session cookie. this is used if you want to ensure that the previous sessions data can't accessed again from thee users browser(for example the django.contrib.auth.logout() functions calls it)

 

# views.py
def get_session_method(request):
    dict=request.session.keys()
    item=request.session.items()
    age=request.session.setdefault("age",25)
    print("before flushing session data")
    request.session.flush()
    print("after flushing session data")
    return render(request,'getsession.html',{'keys':dict,"items":item,"age":age})

#remplate
    {% for key in request.session.keys  %}
      {{key}}
    {% endfor %}

    <h1>For key value </h1>
    {% for key,value in request.session.items  %}
      {{key}}::{{value}}
    {% endfor %}

    <h1>For default</h1>
    {{age}}

 

 

 

 

 

 

 

 


About author

author image

Amrit Panta

Python developer, content writer



3 Comments

Amanda Martines 5 days ago

Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.

Reply

Baltej Singh 5 days ago

Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Marie Johnson 5 days ago

Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.

Reply

Leave a Reply

Scroll to Top