Cookie

HTTP请求是无状态的,不能判断用户是否是登录状态。

什么是Cookie?

 Cookie具体指的是一段小信息,它是服务器发送出来存储在浏览器上的一组组键值对,下次访问服务器时浏览器会自动携带这些键值对,以便服务器提取有用信息。

Cookie的原理

 Cookie具体指的是一段小信息,它是服务器发送出来存储在浏览器上的一组组键值对,下次访问服务器时浏览器会自动携带这些键值对,以便服务器提取有用信息。

在Django中操作Cookie

1.设置Cookie
设置未加密的Cookie:
rep.set_cookie(key,value,...)(key,value为设置的cookies的键和值)
设置加盐的cookie:
rep.set_signed_cookie("key", "val", salt="s10nb", max_age=10)  # 单位是秒
 max_age:设置cookie的保存时间。默认为None,关闭浏览器后cookie消失。一般设置cookie的保存时间为3天或7天
                        例如设置7天:max_age = 60*60*24*7(单位为秒)
 
2.获取Cookie
获取未加密的Cookie:
request.COOKIES['key']
request.COOKIES.get("key", 0)
获取通过加盐加密后的Cookie:
request.get_signed_cookie("key", default=RAISE_ERROR, salt='加密盐')
参数key:为某一cookie对应的键,通过键获取cookie的值
    default:默认值为RAISE_ERROR,需修改为其他的,像0,None,1等等。(没有获取到Cookie,不修改此属性时抛出异常,修改后返回修改的值)
    salt:加密盐。(可任意设置,但是需要保证在获取时的加密盐和设置cookie时的加密盐一致)
   
3.删除cookie
rep.delete_cookie("key") # 删除用户浏览器上之前设置的cookie值
rep.delete_cookie("user") # 删除用户浏览器上之前设置的usercookie值
# 注销用户函数
def logout(request):
    rep = redirect("/login/")
    rep.delete_cookie("user") # 删除用户浏览器上之前设置的usercookie值
    return rep
 
4. Cookie版登陆校验
 1 def check_login(func):
 2     @wraps(func)
 3     def inner(request, *args, **kwargs):
 4         next_url = request.get_full_path()
 5         if request.get_signed_cookie("login", salt="SSS", default=None) == "yes":
 6             # 已经登录的用户...
 7             return func(request, *args, **kwargs)
 8         else:
 9             # 没有登录的用户,跳转刚到登录页面
10             return redirect("/login/?next={}".format(next_url))
11     return inner
12 
13 
14 def login(request):
15     if request.method == "POST":
16         username = request.POST.get("username")
17         passwd = request.POST.get("password")
18         if username == "xxx" and passwd == "dashabi":
19             next_url = request.GET.get("next")
20                 if next_url and next_url != "/logout/":
21                     response = redirect(next_url)
22                 else:
23                     response = redirect("/class_list/")
24                 response.set_signed_cookie("login", "yes", salt="SSS")
25                 return response
26     return render(request, "login.html")
原文地址:https://www.cnblogs.com/aberwang/p/10397590.html