Sessions in Django
Sessions are used for the purpose of handling cookies and improving the security of our web app. They abstract how cookies are received and sent.
- Setting up Cookies :-
In Django, sessions can be enabled in the file “settings.py”, and some lines have to be added between the “MIDDLEWARE_CLASSES” and “INSTALLED_APPS”. This should be done when the project is being created. You should be aware that the “MIDDLE_WARE” classes should have the following:
‘django.contrib.sessions.middleware.SessionMiddleware’
And the “INSTALLED_APPS” should have the following:
‘django.contrib.sessions’
We should now change the login view to save the server side of our username cookie. This is shown in the code given below:
def login(request):
username = ‘not logged in’
if request.method == ‘POST’:
MyForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyForm.cleaned_data[‘username’]
request.session[‘username’] = username
else:
MyForm = LoginForm()
return render(request, ‘loggedin.html’, {“username” : username}
We can then create the view “fmView”, and the form will not be displayed in case the cookie has been set. This is shown in the code given below:
def fmView(request):
if request.session.has_key(‘username’):
username = request.session[‘username’]
return render(request, ‘loggedin.html’, {“username” : username})
else:
return render(request, ‘login.html’, {})
We should now change the file “url.py” so that it can match the new view we have. 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’))
The following is a logout view that will work to delete our cookie:
def logout(request):
try:
del request.session[‘username’]
except:
pass
return HttpResponse(“<strong>You have been logged out.</strong>”)
This can be paired with a logout URL in the file “myapplication/url.py” as shown below:
url(r’^logout/’, ‘logout’, name = ‘logout’),
The following are other useful actions associated with sessions:
- set_expiry (value) – For setting the expiration time of the session.
- get_expiry_age() – For returning the number of the seconds until the session expires.
- get_expiry_date() – For returning the date that the session will expire.
- clear_expired() – For removing the expired sessions from our session store.
- get_expire_at_browser_close() – For returning either “True” or “False”, as determined by whether the session cookies had expired during the time of closing the browser.
- Session Data :-

No comments:
Post a Comment
If you have any doubts. Please let me know.