Django [eleven] cookie-sesson

A session tracking

  We need to look at what is the conversation! The conversation can be understood as a meeting between the client and the server, in a meeting that may contain multiple requests and responses. For example, you make a phone call to 10086, you are the client, while the server is 10086 service personnel. From the moment the two sides to connect the call, the session began, to either hang up the phone indicates the end of the session. During a call, you can make multiple requests to the 10086, so that multiple requests in a single session. The first client sends a request to a server to start the session began, until the end of the customer closed the browser session.

  

  A plurality of shared data in a session request, which is session tracking technology. In one example, the session request is as follows: 

  • Request Bank Home; 
  • Request login (request parameter is the user name and password);
  • Transfer request (Request parameter associated with the transfer of data); 
  • Request credit card payments (request parameter related to the repayment of the data).  

  In this last session of the current user information must be shared in this session, because the login is Joe Smith, Joe Smith then it must be relatively transfers and payments at the time of the transfer and repayment! This shows that we must have the ability to share data in a session. And to achieve this we must rely on the ability of web cookie and session

Two cookie

  The origin of Cookie

    We all know that HTTP protocol is stateless.

    Stateless means each request is independent, its execution and results of previous requests and subsequent requests are not directly related, it is not limited by the foregoing request directly affect the response, it does not directly affect the back request response situation.

    An interesting word to describe the life is only as strike, for the server, each request is new.

    State data can be understood as a client and server created in a given session, and that no state to think that these data will not be retained. Session data generated is we need to be saved, that is to "hold." So Cookie is born under such a scenario.

              And there is a problem, you visit my site, I can not determine that you are not landed, before we learn django, though written many pages, but the user can not see all the pages are landing, as long as he knows the URL on the line, but for our own security, we do not verify ah, what a web site visit, must verify the user's identity, but also what guarantee do, after users have logged on, but also to ensure landed users do not need to repeat the landing, you will be able to access other pages of my website URL, right, but http stateless ah, how to ensure that this thing? At this point we are looking for a cookie.

  What is a Cookie

    First speaking, cookie browser technology, Cookie specifically referring to was a little information, it is the server sends out a bundle of keys stored on the browser, it can be understood as the server to the client a small dessert, the next time you access the server browser will automatically carry these key-value pairs for the server to extract useful information.

  Cookie principles

    Works cookie is: a browser to access the server, with an empty cookie, and then generate content from the server, the browser receives the corresponding stored locally; when the browser visits, the browser will automatically bring the Cookie, so that the server can be judged by the content of this Cookie "who" was.

  View Cookie

    We use the Chrome browser, open the developer tools.    

  

  cookie illustration

    

  Cookie Specification 

  •  Cookie size is 4KB limit; 
  •  A server save up to 20 Cookie on the client browser; 
  •  A browser save up to 300 Cookie, because a browser can access multiple servers.

    The above data is only the HTTP Cookie specification, but in the browser wars of today, some of the browser in order to defeat the opponent, in order to demonstrate their abilities reasons, you might Cookie specification for "extended" some, such as the size of each Cookie is 8KB, You can save up to 500 Cookie and so on! But it may fill your hard drive will not appear! 
Note that different browsers is not shared Cookie's. That is when you use IE to access the server, the server will send IE Cookie, and then save the IE up when you access the server using FireFox, IE is not possible to send Cookie saved to the server.

  Cookie and HTTP Header  

    Cookie is a HTTP request and response headers client and transmitted from the server: 

  • Cookie: request header sent by the client to the server; 
  • Format: Cookie: a = A; b = B; c = C. I.e., away from the plurality of Cookie semicolon;  Set-Cookie: header in response, the server sends to the client; 
  • A Cookie object a Set-Cookie: Set-Cookie: a = A Set-Cookie: b = B Set-Cookie: c = C  

  Cookie coverage 

      If the server then send repeated Cookie will overwrite the old Cookie, for example, a first client request sent by the server is Cookie: Set-Cookie: a = A; a second request is sent by the server: Set-Cookie: a = AA, then the client, leaving only a Cookie, namely: a = AA. 

django page to verify the cookie

Cookie settings

rep = HttpResponse(...)
rep = render(request, ...)

rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='加密盐', max_age=None, ...)

    parameter:

      key, key

      value = '', the value of

      max_age = None, timeout

      expires=None, 超时时间(IE requires expires, so set it if hasn't been already.)

      path = '/', which entered into force Cookie path, / represents the root path, special: cookie root path can be accessed any url of the page

      The domain domain = None, Cookie into force

      secure = False, https transmission

      httponly = False only http protocol transport, can not be acquired JavaScript (not absolute, can get to the bottom of capture may be covered)

Get Cookie

request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)

    parameter:

      default: default value

      salt: Salt Encryption

      max_age: background control expiration

Delete Cookie

Zimbabwe Logout DEF (Request): 
    REP = redirect ( "/ the Login /") 
    rep.delete_cookie ( "the User") # delete usercookie values previously set on the user's browser to 
    return rep

HTML:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% csrf_token %}

用户名:<input type="text" id="i1" name="username">
密码:<input type="text" id="i1" name="password">
<input type="button" value="提交" id="but">
<span class="s1"></span>
</body>
<script src="{% static "jquery-3.4.1.js" %}"></script>
<script>

    $("#but").click(function () {
        var username = $("[name=username]").val();
        var password = $("[name=password]").val();
        var csrf_data = $('[name=csrfmiddlewaretoken]').val();
        $.ajax(
            {
                url:"{% url 'login' %}",
                type:"post",
                data:{
                        name:username,
                        pwd:password,
                        csrfmiddlewaretoken:csrf_data,
                    },
                success:function (data) {
                    if (data==="123"){
                        Alert ( " successful landing " ); 
                        location.href = " {% url " index " %} " 
                    } the else { 
                        $ ( " .s1 " ) .text ( " user name or password is wrong !!! " ) 
                    } 
                } 
            } 
        ) 
    })

 </ Script> 

</ HTML> 

login page
log in page
<! DOCTYPE HTML> 
<HTML lang = " EN " > 
<head> 
    <Meta charset = " UTF-8 " > 
    <title> the Title </ title> 
</ head> 
<body> 

<h1> Welcome to 20 </ h1> 
<a href= "{% url" Zimbabwe Logout "%}"> Log </a> 
</ body> 
</ HTML> 
page after successful login
After the success of the login page

View function:

from django.shortcuts Import the render, HttpResponse, redirect 

# the Create your views here Wallpaper. 
from app01 Import Models 

# decorator, add validation to each page 
DEF wapper (FUNC):
     DEF Inner (Request):
         IF request.COOKIES.get ( " alex " ) == " DSB " :
             # every time you enter a new page must determine whether the cookie 
            RET = FUNC (Request)
             return RET
         the else :
             # If you do not carry the cookie redirected to the login page 
            return redirect("login")
    return inner


@wapper  # index = wapper(index)
def index(request):
    return render(request, "index.html")

# 退出登录删除cookie
def logout(request):
    ret = redirect("login")
    ret.delete_cookie("alex")
    return ret

# 登录页面
def login(request):
    if request.method == "GET" : 

        Return the render (Request, " the login.html " ) 

    the else : 
        name = request.POST.get ( " name " ) 
        pwd = request.POST.get ( " pwd " ) 
        obj = models.Userinfo.objects.all ()
         # judge of the database user name and user input is consistent 
        for info in obj:
             iF name == info.username and pwd == info.password: 
                RET = HttpResponse ( " 123 ")
                 # If the login is successful it is set to give the cookie 
                ret.set_cookie ( " alex " , " DSB " )
                 return RET
         the else :
             return the render (Request, " login.html " ) 

logic function
Logical Functions

URLS:

from django.conf.urls import url
from app01 import views
urlpatterns = [
    url(r'^index/', views.index,name="index"),
    url(r'^login/', views.login,name="login"),
    url(r'^logout/', views.logout,name="logout"),
]

配置路由
Configuring Routing

django page verification in session

Session is a server-side technology, the use of this technology, the server can be created at run time for each user's browser session object of its exclusive, due to the user's browser session is exclusive, so when users access the web server resources, It can be placed in each respective data session when the user access other web resources to go to the server, and then remove the other web resources, user services data from the respective user session.

Although Cookie solved to a certain extent, a "hold" requirements, but due to the 4096 byte maximum support itself Cookie, Cookie and 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. This is the Session.

  The question is, based on the characteristics of the stateless HTTP protocol, the server does not know the visitor "who." Then the aforementioned Cookie will play the role of bridge.

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

  In conclusion: Cookie up for the lack HTTP stateless, let the server know to the people "who"; however Cookie in the form of text stored locally, their security is poor; so we can identify the user through different Cookie, corresponding saving private information and text than 4096 bytes in the Session.

  Further, the above-mentioned fact, Cookie and Session commonality things, not limited to the language and the frame.

Django related methods in Session

注意:这都是django提供的方法,其他的框架就需要你自己关于cookie和session的方法了。
# 获取、设置、删除Session中数据
#取值
request.session['k1'] 
request.session.get('k1',None) #request.session这句是帮你从cookie里面将sessionid的值取出来,将django-session表里面的对应sessionid的值的那条记录中的session-data字段的数据给你拿出来(并解密),get方法就取出k1这个键对应的值

#设置值
request.session['k1'] = 123
request.session.setdefault('k1',123) # 存在则不设置
#帮你生成随机字符串,帮你将这个随机字符串和用户数据(加密后)和过期时间保存到了django-session表里面,帮你将这个随机字符串以sessionid:随机字符串的形式添加到cookie里面返回给浏览器,这个sessionid名字是可以改的,以后再说
#但是注意一个事情,django-session这个表,你不能通过orm来直接控制,因为你的models.py里面没有这个对应关系
#删除值
del request.session['k1']  #django-session表里面同步删除


# 所有 键、值、键值对
request.session.keys()
request.session.values()
request.session.items()


# 会话session的key
session_key = request.session.session_key  获取sessionid的值

# 将所有Session失效日期小于当前日期的数据删除,将过期的删除
request.session.clear_expired()

# 检查会话session的key在数据库中是否存在
request.session.exists("session_key") #session_key就是那个sessionid的值

# 删除当前会话的所有Session数据
request.session.delete()
  
# 删除当前的会话数据并删除会话的Cookie。
request.session.flush()  #常用,清空所有cookie---删除session表里的这个会话的记录,
    这用于确保前面的会话数据不可以再次被用户的浏览器访问
    例如,django.contrib.auth.logout() 函数中就会调用它。

# 设置会话Session和Cookie的超时时间
request.session.set_expiry(value)
    * 如果value是个整数,session会在些秒数后失效。
    * 如果value是个datatime或timedelta,session就会在这个时间后失效。
    * 如果value是0,用户关闭浏览器session就会失效。
    * 如果value是None,session会依赖全局session失效策略。

相关配置
相关配置

Session详细流程解析

视图函数:

复制代码
from django.shortcuts import render, HttpResponse, redirect

# Create your views here.
from app01 import models

# 装饰器,给每个页面加上验证功能
def wapper(func):
    def inner(request):

        if request.session.get("user") == "chao":
            # 1、从cookie中找到sessionid对应的字符串
            # 2、通过 字符串 找到djangosession表中的那条记录,将sessiondata拿出来了,并且解密了,{ 'user':chao}

            # 每次进入新的页面都要判断是否有cookie
            ret = func(request)
            return ret
        else:
            # 如果没有携带cookie就重定向到登录页面
            return redirect("login")
    return inner


@wapper  # index = wapper(index)
def index(request):
    return render(request, "index.html")

# 退出登录删除session
def logout(request):
    # 删除session,浏览器和服务器的都清除了
    request.session.flush()
    return redirect("login")

# 登录页面
def login(request):
    if request.method == "GET":

        return render(request, "login.html")

    else:
        name = request.POST.get("name")
        pwd = request.POST.get("pwd")
        obj = models.Userinfo.objects.all()
        # 判断数据库的用户名和用户输入的是否一致
        for info in obj:
            if name == info.username and pwd == info.password:

                # 设置session
                request.session["user"]=name
                """
                1.    第一件事情,生成一个随机字符串,sessionid: 584c3F7SYiG1qCn2hYQHxSP1eQGu
                2.    第二件事情,加密一些用户信息{"user":"chao"},保存到数据库里面django_session表,
                3.    第三件事情,将,sessionid: 584c3F7SYiG1qCn2hYQHxSP1eQGu放到了cookie里面,
                """
                return  HttpResponse("123")
        else:
            return render(request, "login.html")
复制代码

Django中的Session配置

    Django中默认支持Session,其内部提供了5种类型的Session供开发者使用。

复制代码
1. 数据库Session
SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # 引擎(默认)

2. 缓存Session
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 引擎
SESSION_CACHE_ALIAS = 'default'                            # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置

3. 文件Session
SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # 引擎
SESSION_FILE_PATH = None                                    # 缓存文件路径,如果为None,则使用tempfile模块获取一个临时地址tempfile.gettempdir() 

4. 缓存+数据库
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'        # 引擎

5. 加密Cookie Session
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'   # 引擎

其他公用设置项:
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,默认修改之后才保存(默认)
复制代码

Guess you like

Origin www.cnblogs.com/youxiu123/p/11600606.html