Django:Cookie和session

The origin of Cookie

  • 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.
  • 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.

What is a Cookie

  • Cookie specifically referring to was a small information, which is stored on the server sends out the browser bundle of key-value pairs , the next time you access the server browser will automatically carry these key-value pairs for the server to extract useful information.
  • 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 the server can be judged by the content of this Cookie "who "a.

View Cookie

  • Chrome browser, open the developer attack View

application:

  • log in
  • Save browsing habits
  • Simple Voting

Django operating Cookie

  • Set / Get Cookie

    #第一种方法普通获取/设置:
    #set_cookie         设置
    class Login(View):
        def get(self,request):
            pass
        def post(slef.request):
            #获取重定向对象
          ret = redirect(url)
             ret.set_cookie("login","1")#设置cookie为{"login":"1"}
             ...
    
    #request.COOKIES.get(键)       获取
    def login_required(func):#login_required函数是装饰器函数
        def inner(request,*args,**kwargs):
            login = request.COOKIES.get("login")
            print(login)
            url = request.path_info
            if login != "1":
                return redirect("/login/?return_url={}".format(url))
            ret = func(request,*args,**kwargs)
            return ret
        return inner
    
    @login_required
    def foo(request):...
    
    #第二种方法加密获取:
    #设置
    rep.set_signed_cookie(key,value,salt='加密盐',...)
    参数:
      key  键
        value  值
        max_age = None 超时时间
        expires = None 超时时间(IE浏览器使用)
        path = "/"   Cookie生效的路径
        domain = None   Cookie生效的域名
        secure = False   HTTPS传输
        httponly = False  只能http协议传输,无法被JavaScript获取(但不是绝对,底层抓包可以获取到也可以被覆盖)
    
    #获取
    request.get_signed_cookie('key', default="", salt='', max_age=None)
    参数:
      key    键
        value  值
        max_age   后台控制过期时间
    
    
    ret.set_signed_cookie("login", "1", salt="yan")
            login = request.get_signed_cookie("login",salt="yan",default="")
    
    • Note : When setting the time, can not have a default = "", when the acquired time should default = "", otherwise it will error

When set_signed_cookie provided max_age = 21 seconds, indicating failure after 21 seconds on Cookie

  • By setting set_signed_cookie, get_signed_cookie set_cookie obtain contrast setting, request.COOKIES.get (key) Get

    Both are paired, and none can not be used

    set_signed_cookie will set cookies encrypted, but still show up in Response Cookies, such as setting 1, in the red box:

  • When set secure = True, you can see Response Cookies in loginSecure in play ✔, only HTTPS to log in to continue.

  • httponly = True to log only HTTP protocol

  • delete

    • Uses: cookie values ​​previously set for the deletion of the user's browser user
    ret = redirect("/login/")
    ret.delete_cookie("login")
    • Example: User Exit

      def logout(request):
          ret= redirect("/login/")#退出回到登录页面
          ret.delete_cookie("login")#清除Cookie
          return ret

2.2Session

session from

  • There is a need for something new, it can support more bytes, and he saved on the server, there is high security. This is the Session.
    • Cookie itself due to maximum support 4096 bytes.
    • Cookie itself is stored in the client may be intercepted or stolen.
  • 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 in Session in saving private information and text than 4096 bytes.

  • session key stored on the server for a group of components (to rely cookie), need not be transmitted

  • session data stored on the associated table django-session database

Session method

  • Set session

    request.session[key] = values
    request.session.setdefault('k1',123)
  • Obtaining session

    request.session.get(key,None)
  • Delete session

    del request.session[key]
  • Log achieve verification session

    class Login(View):
        def get(self,request):
            return render(request,"login.html")
        def post(self,request):
            username = request.POST.get("username")
            pwd = request.POST.get("pwd")
            obj = models.User.objects.filter(username=username,pwd=pwd)
            if obj:
                url = request.GET.get("return_url")
                if url:
                    ret = redirect(url)
                else:
                    ret = redirect("/home/")
                #设置session login
                request.session['login'] = 1
    
    
                return ret
    
            return render(request,"login.html",{"error":"用户名密码不正确"})
    
    def login_required(func):#装饰器,判断当前访问状态
        def inner(request,*args,**kwargs):
            #获取session 
            login = request.session.get("login")
            print(login)
            url = request.path_info
            if login != 1:
                return redirect("/login/?return_url={}".format(url))
            ret = func(request,*args,**kwargs)
            return ret
        return inner
    
    
    @login_required
    def home(request):
        return render(request,"home.html")
    
    
    @login_required
    def index(request):
        return render(request,"index.html")
    
    • As can be seen from FIG stored database sessionid = session_key

session flow analysis:

  • flow chart

  • session表

  • Browser

浏览器访问服务器,服务器会自动生成一个随机字符串,设置的值放置在一个字典当中,随机生成的字符串放在Django-session表中session-key字段,数据放在session-data中(加密后),expire_date是超时时间。并保存

把数据库session-key随机字符串放在cookie里返回给浏览器,也就是sessionid。可以理解为sessionid为cookie ,value为返回随机字符串

待到下次访问时会携带cookie(也就是sessionid),服务器会根据cookie从数据库中找到相应数据,再解密返回给浏览器。

由此可知session不能独立使用,必须依赖于cookie使用

session in other ways

  • Get all, key, value, key-value pair

    request.session.keys()
    request.session.values()
    request.session.items()
  • Get session_key

    request.session.session_key
  • Expiration date data deletion

    request.session.clear_expired()
    • Example: Remove invalid data

  • Check whether the session the session key exists in the database

    request.session.exists("session_key")
    • request.session.exists("session_key")

      def index(request):
          ret = request.session.session_key
          result= request.session.exists(ret)
          print(result)#True
          return render(request,"index.html")
  • Delete the current session all the session data, do not delete the cookie

    request.session.delete()
    • Quit, and delete information in the library

      def logout(request):
          ret= redirect("/login/")
          request.session.delete()
          return ret
  • Delete the current session data and delete the session cookie session

    request.session.flush()
    • When this statement is executed

  • Cookie session and set the session timeout (after the timeout, cookie deleted, but there is a database session)

    request.session.set_expiry(value)
      如果value是整整数,session会在相应秒数后失效
      如果value是个datatime获取timedelta,session就会在这个时间后失效
      如果value是0,用户关闭浏览器session就会失效
      如果value是None,session会依赖全局session失效策略
    • Example: request.session.set_expiry (10)

In Django Session Configuration

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,默认修改之后才保存(默认)

Tips :

  • How to see the configuration session

    from django.conf import global_settings
    #ctrl + 鼠标左键点击global_settings进入文件global_settings.py然后搜索session,可以看到配置
  • Cache configuration

    from django.contrib.sessions.backends import db
    #ctrl + 鼠标左键点击db进入文件,通过以下操作可以看到session存在位置

3.JQuery the cookie operation

  • First you need to download Jquery.cookie.js and jquery file, jquery.cookie.js Download

    http://plugins.jquery.com/cookie/

    //连接jquery
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/jquery.cookie.js"></script>
  • Add a cookie

        <script>
            var res = $.cookie("the_cookie","the_value");
            console.log(res);
        </script>

  • Create a cookie and set the effective time is 7 days

    $.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
  • Read cookie

    $.cookie('the_cookie');
  • Delete cookie

    $.cookie('the_cookie', null);   //通过传递null作为cookie的值即可
  • Optional parameters

    $.cookie('the_cookie','the_value',{
        expires:7, 
        path:'/',
        domain:'jquery.com',
        secure:true
    }) 
  • parameter

    expires:(Number|Date)有效期;设置一个整数时,单位是天;也可以设置一个日期对象作为Cookie的过期日期;
    path:(String)创建该Cookie的页面路径;
    domain:(String)创建该Cookie的页面域名;
    secure:(Booblean)如果设为true,那么此Cookie的传输会要求一个安全协议,例如:HTTPS;

4. Common HTTP request header

Protocol header Explanation Examples status
Accept Acceptable respective content type ( Content-Types) Accept: text/plain fixed
Accept-Charset Acceptable character sets Accept-Charset: utf-8 fixed
Accept-Encoding Encoding acceptable response content. Accept-Encoding: gzip, deflate fixed
Cache-Control It is used to specify the current request / reply, and whether caching mechanism. Cache-Control: no-cache fixed
Cookie Prior to the server via Set-Cookiea HTTP protocol cookies (see below) provided Cookie: $Version=1; Skin=new; Fixed: Standard
Host It represents the domain name and port number of the server is listening on the server. If the requested port is a port corresponding to the standard service (80), the port number may be omitted. Host: www.itbilu.com:80``Host: www.itbilu.com fixed
Referer The visit represents the browser before a page can be considered before accessing the links page of the browser to the current page. RefererIn fact, it is Referrerthe word, but to create a standard RFC misspelled, then it would be wrong to use Refererthe. Referer: http://itbilu.com/nodejs fixed
User-Agent The identity of the browser string User-Agent: Mozilla/…… fixed
Content-Type MIME type body of the request (for POST and PUT requests) Content-Type: application/x-www-form-urlencoded fixed

5. Common HTTP response header

Response header Explanation Examples status
Cache-Control All notifications from the server to the client caching mechanism in indicating whether they can be cached object and cache valid time. It seconds Cache-Control: max-age=3600 fixed
Status Header field in response to the Common Gateway Interface, for explaining a state in response to the current HTTP connection. Status: 200 OK
Location 用于在进行重定向,或在创建了某个新资源时使用。 Location: http://www.itbilu.com/nodejs
Server 服务器的名称 Server: nginx/1.6.3 固定
Date 此条消息被发送时的日期和时间(以RFC 7231中定义的"HTTP日期"格式来表示) Date: Tue, 15 Nov 1994 08:12:31 GMT 固定
Connection 客户端(浏览器)想要优先使用的连接类型 Connection: keep-alive``Connection: Upgrade 固定
Content-Length 以8进制表示的请求体的长度 Content-Length: 348 固定

Guess you like

Origin www.cnblogs.com/xujunkai/p/11848043.html