django COOKIE_session

1. Cookies are not within the scope of the http protocol. Because the http protocol cannot maintain state, but in reality, we need to "maintain state", so cookies are born in such a scenario.

The working principle of the cookie is: the content is generated by the server, and the browser saves it after receiving the request; when the browser visits again, the browser will automatically bring the cookie, so that the server can judge this by the content of the cookie. ""

2. Although the cookie solves the need to "maintain state" to a certain extent, because the cookie itself supports a maximum of 4096 bytes, and the cookie itself is saved on the client, it may be intercepted or stolen, so a new thing is needed. It can support more bytes, and it is stored on the server, which has higher security. This is the session.

The problem comes, based on the stateless nature of the http protocol, the server simply does not know who the visitor is. Then the above cookie acts as a bridge.

We can assign a unique id to the cookie of each client, so that when the user visits, through the cookie, the server knows who is coming. Then we save the private information on the server for a period of time according to different cookie ids, such as "account password" and so on.

3. In summary: cookies make up for the lack of http statelessness, letting the server know who is coming from; but the cookies are stored locally in the form of text, and their security is poor; so we use cookies to identify different Users, correspondingly save private information and text over 4096 bytes in the session.

4. In addition, the above-mentioned cookies and session are actually common things, not limited to language and framework

# ---------------------------------------53.5  cookie
def wusanwu(req):
    print('111111111111',req.COOKIES)
    print('111111111111',req.session)
    if req.method=="POST":
        name= req.POST.get('user')
        pwd= req.POST.get('pwd')
        if name=='ouyang' and pwd =='123':
             # Use cookie hold separate 
            # A = the redirect ( '/ index / shouye /') 
            # to the cookie set effective time Add pair 
            # a.set_cookie ( 'bilibili', 'ABCD', the max_age = 10) 
            # return A 

            # using the session on hold 
            req.session [ ' denlu ' ] = True 
            req.session [ ' name ' ] = name
             # Add pair 
            return the redirect ( ' / index / shouye / ' )
     return the render (REQ, ' index.html ')

def shouye(req):
    # if req.COOKIES.get('bilibili',None) == 'abcd':
    #     name = 'ouyang'
    #     return render(req,'首页.html',locals())

    if req.session.get('denlu',None):
        name = req.session.get('name',None)
        return render(req,'首页.html',locals())
    else:
        return redirect('/index/')

 

Guess you like

Origin www.cnblogs.com/oysq/p/12674912.html