Django Cookie和Session

A, cookie and session presentation


  http cookie does not belong to the scope of the agreement, due to the http protocol can not hold, but the reality, but we need to "hold" and therefore cookie is born under such a scenario.

Works cookie is: generated content from the server, the browser receives the request saved locally; when the browser visits, the browser will automatically bring the cookie, so that the server can be judged by the content of the cookie is "Who "a.

Although cookie solved to a certain extent, a "hold" requirements, but due to the cookie itself supports up to 4096 bytes, and the cookie stored in the client itself, may be intercepted or stolen, and therefore there is a need for something new, it support more bytes, and he saved on the server, there is high security. That's session.

  The question is, based on the characteristics of a stateless http protocol, the server does not know the visitor "who." Then the above-mentioned cookie will play the role of bridge.

We can give a unique id cookie assign each client so that users access through the cookie, the server knows to the people "who." Then we id different based on the cookie, private information stored on the server for some time, such as "account password" and so on.

To sum up: cookie to make up for the lack of http stateless, let the server know to the people "who"; but the cookie in the form of text stored locally, their security is poor; so we can identify different users by cookie, corresponding saving private information and text than 4096 bytes in the session.

In addition, the above mentioned cookie and session commonality is actually something that is not limited to language and framework

Second, the principle of the login application

  Introduction previous sections, we have been able to make a landing page, after verifying the correctness of a user name and password to jump to the background page. But the tests also found that if the bypass login page. Direct input background url address can also be accessed directly. This is clearly unreasonable. In fact, we are missing is a cookie and a session with the verification. With this verification process, we can achieve and other Web sites must be logged in to enter the back page.

      Let me talk about this kind of authentication mechanism. Whenever we use a browser to access a landing page, once we have passed the certification. The server sends a random set of unique strings (assumed to be 123abc) to the browser, the cookie is stored in what is called the browser side. And the server will store about their own current state of the user, such as login = true, username = user information hahaha like. But this memory is stored in the form of dictionaries, dictionaries of the only key issue is just a unique cookie value of the user. So if you view session information on the server side, then, in theory, you will see the following dictionary look like


  Because each cookie is unique, so we change the browser on your computer and then landing with a website also needs to be verified again. So why do we just say theoretically see it like this dictionary? Because of safety considerations in the fact that a big dictionary not only for the above key is encrypted 123abc value, value a value { 'login': true, 'username: hahaha'} at the server side is the same encrypted. So we open on the server even if the session information see something like the following also look like

{ '123abc': dasdasdasd1231231da1231231}


Third, the simple use of a cookie

Get cookie: If there is a value on the acquisition, if there is no return None

val = request.COOKIES.get('user','')

Set cookie:

expires: expiration time, a date and time type

path: a valid path, cookie setting only acts on this path and sub-paths

max_age: expiration time, in seconds

        response = redirect('/index/')
            # response.set_cookie('is_login',True,max_age=15) #max_age是以秒计算的,不支持ie
            date =,month=12,day=31)

Delete cookie:


3 based login authentication request process:

A total of three requests
  Note: action taking the form of the path form or / login /
     first request: url: http: // 8080 / login GET request
       a second request: url: http: //127.0. 0.1: 8080 / login POST request user pwd
       third request: url: http: // 8080 / index GET request of the cookie carrying
       it in the index page will take to the cookie, because this is the index there has been a cookie

Note: when you click Submit to complete the request twice, once POST form request form, once the verification successful return response index to jump to the GET request



Login Authentication Code:

from django.shortcuts import render,HttpResponse,redirect
from app01.models import *
import datetime
import  time
# Create your views here.
def login(request):
    if request.method=='POST':
        user = request.POST.get('user','')
        pwd = request.POST.get('passwd')
        user_ret = Userinfo.objects.filter (= User name, pwd = pwd) .first ()
         Print ( ' User name: ' , User)
         Print (user_ret)
         IF user_ret: 
            Response = the redirect ( ' / index / ' )
             # Response. set_cookie ( 'is_login', True, max_age = 15) #max_age is in seconds, does not support IE 
            response.set_cookie ( ' is_login ' , True) # the max_age is in seconds, it does not support IE 
            DATE = ( = 2020 year, month The 12 is =, = Day 31 is ) 
            response.set_cookie ( 'the User ' ,, the Expires = DATE, path = ' / index / ' ) #
             # response.set_cookie () 

            return the Response
         the else :
             return HttpResponse ( ' Login failed ' )
     Print ( " I get request " )
     return   the render ( request, ' the login.html ' ) 

DEF index (request):
     Print ( ' request type: ' , request.method) 
    is_login = request.COOKIES.get ( 'is_login ' )
     IF is_login:
         # After successful login, remove cookies set User 
        username = request.COOKIES.get ( ' User ' )
         ' '' Show Last: 
        1. Remove Last_time Last, if not, null 
        2, provided the login time login_date 
        . 3, the log setting Last_time 
        '' ' 
        Last = request.COOKIES.get ( ' Last_time ' , ' ' )   # . 1 
        login_date the time.strftime = ( ' % Y-% % D% X-M- ' , time.localtime ()) # 2 
        Response = the render (Request,'index.html',{'username':username,'logindate':last})
        return response
        return redirect('/login/')

    # return render(request,'index.html')
View Code


<!DOCTYPE html>
<html lang="zh">
    <meta charset="UTF-8">
<form action="" method="post">
    {% csrf_token %}
    用户名 <input type="text" name="user">of the typethe INPUT<
    Password="password" name="passwd">
    <input type="submit">

View Code


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
<h1>Hi,{{ username }}</h1>
<h2>上次登录时间:{{ logindate }}</h2>
View Code


Guess you like