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

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

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

obj.delete_cookie("cookie_key",path="/",domain=name)

 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: //127.0.0.1: 8080 / login get requests
       the first request: url: http: //127.0. 0.1: 8080 / login post request user pasw
       first request: url: http: //127.0.0.1: 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

urls.py

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

 

views.py

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
     IFis_login: 
        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 / " )

models.py

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

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width">
    <title>用户登录</title>
    <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>
    <style>
        .c1{
            margin-top: 100px;
        }
        .btn{
            width: 130px;
        }
        .c2{
            margin-left: 40px;
        }
    </style>
</head>
<body>
<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>
                </div>
                <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"
                               placeholder="Password">
                    </div>
                </div>
                <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>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
</html>

index.html

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

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 
        request.session.session_key 
  
        # 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:

{"sessionID":"dfhasdjfhkjlcn4352kjdsfhkjsd"}

if  post:

  request.session["is_login"]=True

  request.session["user"]=username

  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"}

request.session.get("IS_LOGON",None)

在django-session表中,进行查询:

s=requset.COOKIE.get("sessionID")
select session-data from django-session where session-key=s

3、示例

views.py

def log_in(request):

    if request.method=="POST":
        username=request.POST['user']
        password=request.POST['pwd']

        user=UserInfo.objects.filter(username=username,password=password)

        if user:
            #设置session内部的字典内容
            request.session['is_login']='true'
            request.session['username']=username

            #登录成功就将url重定向到后台的url
            return redirect('/backend/')

    #登录不成功或第一访问就停留在登录页面
    return render(request,'login.html')




def backend(request):
    print(request.session,"------cookie")
    print(request.COOKIES,'-------session')
    """
    这里必须用读取字典的get()方法把is_login的value缺省设置为False,
    当用户访问backend这个url先尝试获取这个浏览器对应的session中的
    is_login的值。如果对方登录成功的话,在login里就已经把is_login
    的值修改为了True,反之这个值就是False的
    """

    is_login=request.session.get('is_login',False)
    #如果为真,就说明用户是正常登陆的
    if is_login:
        #获取字典的内容并传入页面文件
        cookie_content=request.COOKIES
        session_content=request.session

        username=request.session['username']

        return render(request,'backend.html',locals())
    else:
        """
        如果访问的时候没有携带正确的session,
        就直接被重定向url回login页面
        """
        return redirect('/login/')



def log_out(request):
    """
    直接通过request.session['is_login']回去返回的时候,
    如果is_login对应的value值不存在会导致程序异常。所以
    需要做异常处理
    """
    try:
        #删除is_login对应的value值
        del request.session['is_login']
        
        # OR---->request.session.flush() # 删除django-session表中的对应一行记录

    except KeyError:
        pass
    #点击注销之后,直接重定向回登录页面
    return redirect('/login/')

template

===================================login.html==================
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

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


</body>
</html>


===================================backend.html==================

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

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

</body>
</html>

 

4、session存储的相关配置

 (1)默认的是数据库配置:        

Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。
  
a. 配置 settings.py
  
    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,默认修改之后才保存(默认)

 

(2)缓存配置

a. 配置 settings.py
  
    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,默认修改之后才保存

 

(3)文件配置

a. 配置 settings.py
  
    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

Origin www.cnblogs.com/lida585/p/10990946.html