Tuesday, 20 July 2021

*Episode 14* DJANGO (Handling Cookies of Django)

 


Handling Cookies


    Sometimes, we might need our web app to store information about each visitor to our website. Note that cookies will always be stored on the client side of our web app and they may work or not work.


     Let’s demonstrate how cookies work in Django by creating a login app as we did previously. The app will log you in for a number of minutes and once the time has expired, you will be logged out of the app. For this purpose, two cookies have to be set up. These include the “username” and “last_connection”. The login view has to be changed to the following:


from django.template import RequestContext

def login(request):

username = “not yet logged in”

if request.method == “POST”:

#Getting our posted form

MyForm = LoginForm(request.POST)

if MyForm.is_valid():

username = MyForm.cleaned_data[‘username’]

else:

MyForm = LoginForm()

response = render_to_response(request, ‘loggedin.html’, {“username” :

username},

context_instance = RequestContext(request))

response.set_cookie(‘last_connection’, datetime.datetime.now())

response.set_cookie(‘username’, datetime.datetime.now())

return response


     The method “set_cookie” is used for the purpose of setting cookies as shown in the above code. The values for all of our cookies have to be returned as a string.


It is now time for us to create a “fmView” for our login form, so the form will not be displayed if the cookie has been set and is no more than 5 seconds old. This is shown in the code given below:


def fmView(request):

if ‘username’ in request.COOKIES and ‘last_connection’ in request.COOKIES:

username = request.COOKIES[‘username’]

last_connection = request.COOKIES[‘last_connection’]

last_connection_time = datetime.datetime.strptime(last_connection[:-7],

“%Y-%m-%d %H:%M:%S”)

if (datetime.datetime.now() - last_connection_time).seconds < 5:

return render(request, ‘loggedin.html’, {“username” : username})

else:

return render(request, ‘login.html’, {})

else:

return render(request, ‘login.html’, {})


     As shown in the code given below, for us to access the cookie that has been used, we use the “COOKIES attribute (dict)” of our request. Now we must change the URL in the file “url.py” so that it matches with the current view. This is shown below:


from django.conf.urls import patterns, url

from django.views.generic import TemplateView

upatterns = patterns(‘myapplication.views’,

url(r’^connection/’,‘formView’, name = ‘loginform’),

url(r’^login/’, ‘login’, name = ‘login’))


  • Testing Cookies :-

    The “request” object in Django provides us with some methods that can help us in testing of cookies. Examples of such methods include: “set_test_cookie()”, “test_cookie_worked()” and “delete_test_cookie()”. In one of your views, you are expected to create a cookie, and then test it in another view. To test cookies, you need two cookies, as you will have to wait and see if the client has accepted the cookie from the server.


    In the view you created previously, add the following line:


request.session.set_test_cookie()


     It is a good idea to ensure that this line is executed. Set it as the first line in the view and ensure that it is outside any conditional block. In the second view, add the following code at the top to ensure that it is executed:


if request.session.test_cookie_worked():

print “>>>> TEST COOKIE HAS WORKED!”

request.session.delete_test_cookie()


  • Client Side Cookies :-

    Now that you are sure that cookies work, you need to implement a site visit counter by making the concept of cookies. To achieve this, you will have to implement two cookies:

    one that will be used for keeping track of the number of times that a user visits the website, and another cookie for tracking the last time that the user visited the site.


     The following code best demonstrates this:


def index(request):

context = RequestContext(request)

category_list = Category.objects.all()

context_dict = {‘categories’: category_list}

for category in category_list:

category.url = encode_url(category.name)

page_list = Page.objects.order_by(‘-views’)[:5]

context_dict[‘pages’] = page_list

#### NEW CODE ####

# Obtain the Response object early so as to add the cookie information.

response = render_to_response(‘myfolder/index.html’, context_dict, context)

# Get number of visits to our site.

#Use the COOKIES.get() function for obtaining the visits cookie.

# In case the cookie exists, the returned value will be casted to an integer.

# If the cookie does not exist, we will default to zero and then cast that.

visits = int(request.COOKIES.get(‘visits’, ‘0’))

# Do you find the last_visit cookie?

if ‘last_visit’ in request.COOKIES:

# Yes it exists! Get the value of the cookie.

last_visit = request.COOKIES[‘last_visit’]

# Casting our value to a date/time object in Python.

last_visit_time = datetime.strptime(last_visit[:-7], “%Y-%m-%d %H:%M:%S”)

# If it has been more than one day since the user’s last visit…

if (datetime.now() - last_visit_time).days > 0:

# …reassign its value to +1 of which it was before…

response.set_cookie(‘visits’, visits+1)

# …and then update the last visit cookie, also.

response.set_cookie(‘last_visit’, datetime.now())

else:

# Cookie last_visit does not exist, so make it to your current date/time.

response.set_cookie(‘last_visit’, datetime.now())

# Return the response back to user, and update any cookies that need changing.

return response

#### END NEW CODE ####


     As you may have noticed, the majority of the above code is for checking the current date and time. This can only work after we have included the “datetime” module for Python. To do this, just add the following import statement at the top of your code:


from datetime import datetime


👈Episode 13(D).                                          Episode 15(D)👉

Share This Post

PRINT THIS POST

No comments:

Post a Comment

If you have any doubts. Please let me know.

Featured post

*Episode 1* MCQ for Govt. Job/ Private Job/ MNCs

  Topic:- One Word Substitution 1) Especially skilled in storytelling  Answer:- Raconteur 2) Fear of loneliness Answer:- Eremophobia  3) Usa...