Django Introduction (eight) cookies and session

Source: Internet
Author: User

In the previous sections we have been able to create a landing page, after verifying the correctness of the user name and password to jump to the background page. But the test also found that if the landing page is bypassed. Direct input to the background of the URL address can also be directly accessed. This is obviously unreasonable. What we are missing is the validation of cookies and session mates. With this verification process, we can implement the same as other sites must log in to enter the background page.


Let's start with this certification mechanism. Whenever we use a browser to access a landing page, once we pass the certification. The server side sends a random set of unique strings (assuming 123ABC) to the browser side, which is stored on the browsing side of what is called a cookie. The server side will also store the user's current state, such as Login=true,username=hahaha user information. But the store is stored in a dictionary, and the only key to the dictionary is the only cookie value that has just been sent to the user. So if you look at the session information on the server side, you'll theoretically see a dictionary like this

{'123abc': {' login ': true, ' Username:hahaha '}}

Because each cookie is unique, we also need to verify that we have to change the browser on the computer and then log on to the same website. So why do we just see this dictionary in theory? Because in the security considerations, in fact, the above large dictionary is not only the key value 123ABC is encrypted, value {' Login ': true, ' Username:hahaha ' is also encrypted on the server side. So, even if we open the session information on the server, we see something similar to the following.

{'123abc':d asdasdasd1231231da1231231}

Using a picture of another great God, you can see the relationship between the cookie and the session more intuitively.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7D/5C/wKioL1bmwJqQWT79AACFVu-rqIs465.gif "title=" 0_ 132156434454ee.gif "alt=" Wkiol1bmwjqqwt79aacfvu-rqis465.gif "/>




Now that we know the principle, we'll use code to implement it.


Create two html,login.html in the Templates directory to be responsible for the login page first. Backend page represents a background page

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7D/5D/wKioL1bm3rygxB5QAAAoQMv4T8o844.png "title=" 1.png " alt= "Wkiol1bm3rygxb5qaaaoqmv4t8o844.png"/>

Login.html

<! Doctype html>


Backend.html

<! Doctype html>


The second step is to edit the views.py file under the APP01 application and write the Code logic section

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7D/5D/wKioL1bm4QnCtWaCAAAwVBjCprc461.png "title=" 1.png " alt= "Wkiol1bm4qnctwacaaawvbjcprc461.png"/>

views.py

# /usr/bin/env python# coding:utf-8from django.shortcuts import renderfrom  Django.shortcuts import redirectdef login (Request):    if  request.method== "POST":         username=request. post[' username ']        pwd=request. post[' passwd ']        if username== ' abc '  and pwd== ' 123 ' :             #设置session内部的字典内容              request.session[' Is_login ']= ' true '              request.session[' username ']= ' abc '               #登录成功就将url重定向到后台的url              return redirect ('/backend/')    &nBSP; #登录不成功或第一访问就停留在登录页面     return render (Request, ' login.html ') def backend ( Request):     "" "     here must use the Get () method of the Read dictionary to set Is_login value by default to false,      when a user accesses backend this URL first tries to get the value of the     is_login in the corresponding session of this browser. If the login succeeds, the value of is_login     is changed to true in login, and the value is False      ""     is_login=request.session.get (' Is_login ', False)      #如果为真, It means that the user is the normal login     if is_login:        # Gets the contents of the dictionary and passes in the paging file         cookie_content=request. cookies        session_content=request.session         username=request.session[' username ']         Return render (Request, ' backend.html ', &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;              {              ' Cookie_content ':cookie_content,              ' Session_content ':session_content,              ' username ':username                       })      else:         "" "         Redirect the URL back to the login page if you are not carrying the correct session,         at the time of the visit           "" "        return redirect ('/login/ ') def logout (Request):     "" "     direct via request.session[' Is_login '] Back to return, &NBSP;&NBSP;&NB.sp;  if is_login corresponding value value does not exist, it causes a program exception. So      need to do exception handling      ""     try:          #删除is_login对应的value值         del  request.session[' Is_login ']    except keyerror:         pass     #点击注销之后, redirect directly back to login page     return redirect ('/login /‘)


The third step is to edit the urls.py file under the Mydjango directory. To set the binding relationship of a function to a page

urls.py

From django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [url (r ' ^admin/'), admin.site.urls), url (r ' ^login/', views.login), url (r ' ^backend/', views.backend), url (r ' ^logout/', views.logout), ]

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7D/60/wKiom1bm4D7AGoi8AADg0sOk10k285.png "title=" 1.png " alt= "Wkiom1bm4d7agoi8aadg0sok10k285.png"/>


Finally, when you open the browser directly to the/backend/page, you are redirected directly to the/login/

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/7D/5D/wKioL1bm4Ynh_bOzAABPcTDBX40769.png "title=" 1.png " alt= "Wkiol1bm4ynh_bozaabpctdbx40769.png"/>


Enter the/backend/page only after you have entered the correct username and password

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/7D/60/wKiom1bm4UOjEwzlAAE9se9_78U441.png "title=" 1.png " alt= "Wkiom1bm4uojewzlaae9se9_78u441.png"/> from which we see a few points:

1, login page correctly login, background page can get to the browser to carry the cookie.

2, the first line of SessionID is actually the cookie value

3, session content is encrypted, from the client to get the content of the session

4, the server can use the preset key value to remove the contents of the session and print to the previous paragraph


View cookies from Firefox browser

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/7D/5D/wKioL1bm5aLicB3pAAC_XkZOUds501.png "title=" 1.png " alt= "Wkiol1bm5alicb3paac_xkzouds501.png"/>


Django's session is stored in the database by default, and we'll go to the database to see what the real session is.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7D/5D/wKioL1bm5imRTMYYAABvKzZiJig955.png "title=" 1.png " alt= "Wkiol1bm5imrtmyyaabvkzzijig955.png"/>

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7D/60/wKiom1bm6EHiV1i0AADUm8yxkhs649.png "title=" 1.png " alt= "Wkiom1bm6ehiv1i0aadum8yxkhs649.png"/>


Let's take a final look at the cookie and session knowledge points

First, the operation of cookies


Gets the cookie:request. Cookies[key]


Set Cookie:response.set_cookie (Key,value)


Because cookies are stored on the client's computer, jquery can also manipulate cookies.

<script src= '/static/js/jquery.cookie.js ' ></script>$.cookie ("List_pager_num", 30,{Path: '/'});


Second, the operation session (session by default on the server side for 15 days)


Get Session:request.session[key]


Set Session:reqeust.session[key] = value


Delete Session:del Request.session[key]

(This deletion is actually to update the database's session_data to a different value, and not immediately deleted)


Request.session.set_expiry (value) * If value is an integer, the session will expire after a few seconds. * If value is a datatime or timedelta,session, it will expire after this time. * If value is 0, the user closes the browser session will expire. * If value is none,session, it will depend on the global session expiration policy.

See MORE:


https://docs.djangoproject.com/en/1.9/topics/http/sessions/


http://docs.30c.org/djangobook2/chapter14/


https://docs.djangoproject.com/en/1.9/ref/settings/#settings-sessions


This article from "Thunderbolt Tofu" blog, declined reprint!

Django Introduction (eight) cookies and session

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.