【Django】Cookie

@

Cookie Introduction


The origin of Cookie

We all know that == HTTP protocol is stateless ==.

== stateless means each request is independent == request after its execution and results of previous requests and are not directly related, it is not limited by the foregoing request response directly affect, and It does not directly affect the response of the latter request.

If only shown signs of life, for the server, each request is new.

== state can be understood as both client and server data generated in a given session. ==
== no state can be understood that these data will not be retained ==.
Data generated in the session is that we need to save, that is to "hold", so Cookie was born. in such a scenario
***

What is a Cookie

Cookie specifically referring to was a little information, it is == server sends out a bundle of keys stored on the browser to ==. The next time you access the server browser will automatically carry these key-value pairs for the server to extract useful information.
Cookie itself supports up to 4096 bytes.
***

Cookie principles

Generated by 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

We use the Chrome browser, open the developer tools:
Here Insert Picture Description

Operation Cookie


Get Cookie

def login(request):
    # 获取Cookie:
    ret = request.COOKIES['user']
    # ret = request.COOKIES.get('user')
    # request.get_signed_cookie(key, salt='user', default='')
    # request.get_signed_cookie('user', default=RAISE_ERROR, salt='', ax_age=None)
    return render(request, 'login.html')

get_signed_cookie method parameters:

  • default: default value
  • salt: Salt Encryption
  • max_age: background control expiration
    ***
def test(request):
    rep = HttpResponse('is ok')
    # 设置Cookie:
    rep.set_cookie('user', 'zyk')
    # rep.set_signed_cookie('user', 'zyk', salt="加盐")
    return rep

Review the settings of Cookie, as shown:
Here Insert Picture Description

set_cookie method parameters:

  • key: the key.
  • value = '': value.
  • max_age = None: timeout.
  • expires = None: Specifies IE browser timeout (IE requires> expires, so set it if has not been already.).
  • path = '/': Cookie path in force / path representation with special: cookie with the path of the page can be accessed any url's.
  • domain = None: Cookie domain name in force
  • secure = False: https transmission
  • httponly = False: Only http transmission protocol, JavaScript can not be acquired (not absolute, can get to the bottom of capture may be covered).
    ***

Delete Cookie

def test(request):
    rep = HttpResponse('is ok')
    # 删除Cookie:
    rep.delete_cookie('user')
    return rep

Cookie landing version check:

from django.shortcuts import render, redirect, HttpResponse
from blog01 import models


# 装饰器函数
def login_required(fn):
    """如果未登陆,将返回login页面"""
    def inner(request, *args, **kwargs):
        print(request.COOKIES.get('is_login'))
        if request.COOKIES.get('is_login') != '1':
            # 获取当前url路径
            next = request.path_info
            return redirect('/login/?next=%s' % next)
        ret = fn(request, *args, **kwargs)
        return ret
    return inner


# 登陆功能
def login(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if models.Userinfo.objects.get(name=user, pwd=pwd):
            # 提取跳转之间访问的页面
            next = request.GET.get('next')
            rep = redirect(next) if next else redirect('/home/')
            # 设置Cookie,  max_age=1:指定过期时间为1秒
            rep.set_cookie('is_login', '1', max_age=1)
            return rep
    return render(request, 'login.html')


@login_required
def home(request):
    return HttpResponse("我是home页面")


@login_required
def home01(request):
    return HttpResponse("我是home01页面")

Guess you like

Origin www.cnblogs.com/gqy02/p/11307179.html