cookie是客户端浏览器上的一个文件(键值对)
用户在登录成功后,服务器会加上键值对,跟数据一起返回给浏览器,这个键值对会保存在浏览器上。
当用户在浏览器上访问需要登录后的页面才能访问的页面时,服务器端会从请求的cookie里get之前放在浏览器上的key,如果有就直接验证通过,返回访问页面。
实例:
视图函数:
def login(request): dic = { 'nav':{'pwd': '123456'}, 'nac':{'pwd': '123123'} } username = request.POST.get('username') passwd = request.POST.get('passwd') user = dic.get(username) if not user: res = render(request,'login.html') else: if passwd == user['pwd']: res = redirect('/index/') # 设置cookie,关闭浏览器失效 res.set_cookie('username1',username) # 设置cookie,多少秒之后失效 # res.set_cookie('username1',username,max_age=10) # import datetime # current_date = datetime.datetime.utcnow() # current_date = current_date + datetime.timedelta(seconds=5) # 设置cookie,多少秒之后失效,并设置只有/index这个url生效 # res.set_cookie('username1', username, expires=current_date,path='/index') return res def index(request): username = request.COOKIES.get('username1') print(request.COOKIES) if not username: return redirect('/login/') return render(request, 'index.html',{'username':username})
前端页面:
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="POST"> {% csrf_token %} <input type="text" name="username"> <input type="password" name="passwd"> <input type="submit" value="提交"> </form> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>登录成功 {{ username }}</h1> </body> </html>
1、获取Cookie:
request.COOKIES.get('key') request.get_signed_cookie(key, default=RAISE_ERROR, salt='加密盐', max_age=None) //加密 参数: default: 默认值 salt: 加密盐(随机字符串,get_signed_cookie与set_signed_cookie的随机字符串必须一样。) max_age: 后台控制过期时间
2、设置Cookie:
rep = HttpResponse(...) 或 rep = render(request, ...)或rep =redirect('/index/') rep.set_cookie(key,value,max_age=10,...) rep.set_signed_cookie(key,value,salt='加密盐',...) //加密 参数: key, 键 value='', 值 max_age=None, 超时时间(将超时时间设置为当前时间就会清空cookie) expires=None, 超时时间(IE requires expires, so set it if hasn't been already.) path='/', Cookie生效的路径,/ 表示根路径,特殊的:跟路径的cookie可以被任何url的页面访问 domain=None, Cookie生效的域名 secure=False, https传输 httponly=False 只能http协议传输,无法被JavaScript(用document.cookie)获取(不是绝对,底层抓包可以获取到也可以被覆盖)
注销登录,即设置超时时间为当前时间,来清空cookie
import datetime current_date = datetime.datetime.utcnow() rep = redirect('/index/') rep.set_cookie('cookiekey','cookievalue',expires=current_date)
cookie验证装饰器
FBV:
def auth(func):
def inner(reqeust,*args,**kwargs):
v = reqeust.COOKIES.get('username111')
if not v:
return redirect('/login/')
return func(reqeust, *args,**kwargs)
return inner
CBV:
from django import views
from django.utils.decorators import method_decorator
@method_decorator(auth,name='dispatch')
class Order(views.View):
# @method_decorator(auth)
# def dispatch(self, request, *args, **kwargs):
# return super(Order,self).dispatch(request, *args, **kwargs)
# @method_decorator(auth)
def get(self,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
def post(self,reqeust):
v = reqeust.COOKIES.get('username111')
return render(reqeust,'index.html',{'current_user': v})
实例:
from django.shortcuts import render,redirect # Create your views here. def auth(func): def inner(request,*args,**kwargs): username = request.COOKIES.get('username1') print(request.COOKIES) if not username: return redirect('/login/') else: ret = func(request,*args,**kwargs) return ret return inner def login(request): dic = { 'nav':{'pwd': '123456'}, 'nac':{'pwd': '123123'} } username = request.POST.get('username') passwd = request.POST.get('passwd') user = dic.get(username) if not user: res = render(request,'login.html') return res # else: if passwd == user['pwd']: res = redirect('/index/') # 设置cookie,关闭浏览器失效 res.set_cookie('username1',username) # 设置cookie,多少秒之后失效 # res.set_cookie('username1',username,max_age=10) # import datetime # current_date = datetime.datetime.utcnow() # current_date = current_date + datetime.timedelta(seconds=5) # 设置cookie,多少秒之后失效,并设置只有/index这个url生效 # res.set_cookie('username1', username, expires=current_date,path='/index') return res else: return render(request,'login.html') @auth def index(request): username = request.COOKIES.get('username1') # print(request.COOKIES) # if not username: # return redirect('/login/') return render(request, 'index.html',{'username':username})

浙公网安备 33010602011771号