Django learning: cookie and 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

1, get Cookie

request.COOKIES.get ( "islogin", None) # If you get there, not just defaults to none

2. Set Cookie

  = the redirect obj ( "/ index /") 
  obj.set_cookie ( "islogin", True) # Set cookie values, the parameters noted here, a is a bond, a is a value 
  obj.set_cookie ( "haiyan", "344 ", 20 ) # 20 represents the expiration time 
  obj.set_cookie ( "username", username)

3. Delete Cookie


 Login authentication Example:

Some need to know

A total of three requests
  Note: action taking the form of the path form or / login /
     first request: url: http: // 8080 / login get requests
       the first request: url: http: //127.0. 0.1: 8080 / login post request user pasw
       first request: url: http: // 8080 / index post a request carrying the cookie
       so the index page will take to the cookie, because this is the index there has been a cookie

1 from app01 import views
2 urlpatterns = [
3     url(r'^admin/',,
4     url(r'^login/', views.login),
5     url(r'^index/', views.index),
6 ]

from django.shortcuts Import the render, the redirect, the HttpResponse
 from app01 Import Models 
# here Wallpaper the Create your views. 
DEF Login (Request): 
    IF request.method == " the POST " : 
        Print ( " all request data " , of request.POST) 
        username = request.POST. GET ( " username " ) 
        password = request.POST. GET ( " password " ) 
        # View the database user name and password entered by the user whether the contrast value in the database 
        retModels.UserInfo.objects.filter = (username = username, password = password)
         IF RET: # If the username and password are correct, the login is successful 
            Print (Request.Cookies) # { ' csrftoken ' : ' 1EaTcdQlxdwtR0eXu4uDqEHElEpOlDRJoSAd7TfA7cBDxAyxADVPbIKaZk6J0DVB ' } 
            # Since http protocol is stateless, you do not know the login finish who logged in, when people know your home page url, you can log in. There is no privacy as the 
            # which was to use a cookie 
            obj = redirect ( " / index / " ) 
            obj.set_cookie ( " islogin " , True) # set a cookie value, pay attention to where the arguments, one key, one value 
            obj.set_cookie ( " Haiyan" , " 344 " , 20 ) # 20 represents the expiration time 
            obj.set_cookie ( " username " , username)
             return obj
         the else :
             return the render (Request, " login.html " )
     the else :
         return the render (Request, " login.html " ) 
DEF index (Request): 
    is_login . Request.Cookies = gET ( " islogin " , none) # get cookie, get there, do not get none
        username . = Request.Cookies GET ( " username " ) 
        Print (username) 
        return the render (Request, " index.html " , { " username " : username})
     the else : # If you do not get the value, it has been logged page to get in
         return redirect ( " / the Login / " )

1 class UserInfo(models.Model):
2     username =models.CharField(max_length=32)
3     password =models.CharField(max_length=32)


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
            margin-top: 100px;
            width: 130px;
            margin-left: 40px;
<div class="container">
    <div class="row">
        <div class="c1 col-md-5 col-md-offset-3">
            <form class="form-horizontal" action="/login/" method="post" novalidate>
                {% csrf_token %}
                <div class="form-group">
                    <label for="username" class="col-sm-2 control-label">用户名</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" id="username" placeholder="Email" name="username">
                <div class="form-group">
                    <label for="password" class="col-sm-2 control-label">密码</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" name="password" id="password"
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">登录</button>
                        <button type="submit" class="btn btn-success c2">注册</button>



<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
<h1>hello{{ username }}</h1>

cookie stored in the client

Advantages: Data stored in the client. Reduce the pressure on the service side, to improve site performance

Cons: security is not high, it is easy to see the client or crack user session information



Four, session's simple to use

1, the basic operation (need to know)

Copy the code
1, session set value 
    makes request.session [ "session_name"] = "ADMIN" 
2, obtaining the value of session 
    session_name makes request.session = ( "session_name") 
. 3, delete the session value 
    del request.session [ "session_name"] delete a set of keys value 
    request.session.flush () to delete a record 
4, detecting whether the operation session value 
    if "session_name" is request.session:
Copy the code


Other operations

Copy the code
. 5, GET (Key, default = None) 
fav_color = request.session.get ( 'fav_color', 'Red') 
. 6, POP (Key) 
fav_color = request.session.pop ( 'fav_color') 
. 7, Keys () 
. 8 , items () 
9, setDefault () 
10, flush () delete the current session data and deletes the session Cookie. 
            This is used to ensure that the previous session data can not be accessed again the user's browser, 
            for example, django.contrib.auth.logout () function is called it. 
11 user session random string of 
        # expiration date will be less than the current date data to remove all the Session 
        request.session.clear_expired () 
        random string # to check whether the user session in the database 
        request.session.exists ( " session_key ") 
        # delete all the current user Session data 
        request.session.delete (" session_key ")
        request.session.set_expiry (value) 
            * If the value is an integer, session will expire after some number of seconds. 
            * If the value is datatime or timedelta, session will expire after this time. 
            * If the value is 0, the user closes the browser session will fail. 
            * If the value is None, session will depend on the global session expiration policy.
Copy the code

2, FIG flow analysis

Since the cookie will all the information is stored in the client, which is the browser, it will lead to unsafe, so quotes session, but the session is not only easy to use but you must session and cookie with which to use.

session will save the information on the server side.

session principle analysis process:


if  post:



  return redirect("/index/”)

Django will do three things:

  1, create a random string. If s = "sdgsdfg4565dfgsdfgsdf" 

  2, the django-session table, a record is added

    django-session has three fields, namely: session_key, session_data, expire_data

      SQL: 语句: insert into django-session values (s,"{"IS_LOGON":True,"USER":egon}",12321)

  3、给浏览器设置sessionID:  obj.set_cookie("sessionID",s)  


/home/ ----> {"sessionID":"fasdlkfjsakdl324ada2adhdjlka99"}



select session-data from django-session where session-key=s


def log_in(request):

    if request.method=="POST":


        if user:

            return redirect('/backend/')

    return render(request,'login.html')

def backend(request):

    if is_login:


        return render(request,'backend.html',locals())
        return redirect('/login/')

def log_out(request):
        del request.session['is_login']
        # OR---->request.session.flush() # 删除django-session表中的对应一行记录

    except KeyError:
    return redirect('/login/')


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">

<form action="/login/" method="post">
    <p>用户名: <input type="text" name="user"></p>
    <p>密码: <input type="password" name="pwd"></p>
    <p><input type="submit"></p>



<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">

<h3>hello {{ username }}</h3>
<a href="/logout/">注销</a>





Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。
a. 配置
    SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # 引擎(默认)
    SESSION_COOKIE_NAME = "sessionid"                       # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
    SESSION_COOKIE_PATH = "/"                               # Session的cookie保存的路径(默认)
    SESSION_COOKIE_DOMAIN = None                             # Session的cookie保存的域名(默认)
    SESSION_COOKIE_SECURE = False                            # 是否Https传输cookie(默认)
    SESSION_COOKIE_HTTPONLY = True                           # 是否Session的cookie只支持http传输(默认)
    SESSION_COOKIE_AGE = 1209600                             # Session的cookie失效日期(2周)(默认)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False                  # 是否关闭浏览器使得Session过期(默认)
    SESSION_SAVE_EVERY_REQUEST = False                       # 是否每次请求都保存Session,默认修改之后才保存(默认)



a. 配置
    SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 引擎
    SESSION_CACHE_ALIAS = 'default'                            # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置
    SESSION_COOKIE_NAME = "sessionid"                        # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串
    SESSION_COOKIE_PATH = "/"                                # Session的cookie保存的路径
    SESSION_COOKIE_DOMAIN = None                              # Session的cookie保存的域名
    SESSION_COOKIE_SECURE = False                             # 是否Https传输cookie
    SESSION_COOKIE_HTTPONLY = True                            # 是否Session的cookie只支持http传输
    SESSION_COOKIE_AGE = 1209600                              # Session的cookie失效日期(2周)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False                   # 是否关闭浏览器使得Session过期
    SESSION_SAVE_EVERY_REQUEST = False                        # 是否每次请求都保存Session,默认修改之后才保存



a. 配置
    SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # 引擎
    SESSION_FILE_PATH = None                                    # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir()        
    SESSION_COOKIE_NAME = "sessionid"                          # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串
    SESSION_COOKIE_PATH = "/"                                  # Session的cookie保存的路径
    SESSION_COOKIE_DOMAIN = None                                # Session的cookie保存的域名
    SESSION_COOKIE_SECURE =False # Https whether transmission cookie 
    SESSION_COOKIE_HTTPONLY = True # whether the Session cookie only supports http transmission 
    SESSION_COOKIE_AGE = 1209600                                 # Session of cookie expiration date (two weeks) 
    SESSION_EXPIRE_AT_BROWSER_CLOSE is = False # if you close the browser makes Session expired 
    SESSION_SAVE_EVERY_REQUEST = False # whether each request are saved Session, was saved after modifying default


Guess you like