Monday, 26 July 2021

*Episode 15* DJANGO (Sessions in Django)


 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 :-

    To be more secure, it is recommended that we store our session data on the server side.
The session ID cookie that has been stored on the client side can be used for the purpose
of unlocking the data. The example given below best demonstrates how this can be done:

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 ####
if request.session.get(‘last_visit’):
# The session has the value for last visit
last_visit_time = request.session.get(‘last_visit’)
visits = request.session.get(‘visits’, 0)
if (datetime.now() - datetime.strptime(last_visit_time[:-7], “%Y-%m-%d
%H:%M:%S”)).days > 0:
request.session[‘visits’] = visits + 1
request.session[‘last_visit’] = str(datetime.now())
else:
# The get will return None, as the session doesn’t have a value for user’s last visit.
request.session[‘last_visit’] = str(datetime.now())
request.session[‘visits’] = 1
###
# END NEW CODE ####
# Render and then return rendered response back to user.
return render_to_response(‘myfolder/index.html’, context_dict, context)


     It is recommended that you delete the client-side cookies before you begin to make use of the session-based data. You should do this from the browser’s developer tools and delete each of the cookies individually. You can also choose to entirely clear the cache for your
browser.

👈Episode 14(D)।                                                                            Episode 16(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...