Thursday, May 1, 2014

Session management: Login and logout using cookies

Hey! I know I've not posted for a long time. Truthfully, there was not much new. But there is now, so here I am! Today we'll see how to manage login and logout sessions. If you've noticed when you're on Facebook, if you accidentally close the window, reopen it and go to facebook.com, your homepage is displayed. This is because your browser has received cookies from Facebook and you're still logged in in their database.
For those who don't know, cookies are small packets of information that the user's browser stores in its cache. We'll see how to manage them in Django.

I assume you're familiar with how to use dictionaries in Python. So to create a cookie, simply do the following:
request.session[key] = value

request.session is a dictionary where all cookie data gets stored. For example,
request.session['username'] = 'someUser'

This will store the username as someUser in the browser. Do this when the user logs in. This value can be accessed many views and apps later.
In case the cookie is not erased while logging out then the next time the user opens the site he will stil be logged in.
If no one is logged in and you try to access request.session['username'], it raises a KeyError. You can use this with exception handling to check if anyone is logged into your site.

try:
    username = request.session['username']
    return HttpResponse (username)
except KeyError:
    return HttpRepsonse ("No one is logged in")

On log out, delete the cookies.
del request.session ['username']

Like this, delete all the relevant ones.
Cheers!

No comments:

Post a Comment