------https://www.cnblogs.com/liuqingzheng/articles/8990027.html
需求情形一:正常设置cookie
set_cookie(key,value,max_age,expires,path,domain,secure,httponly)
def test_cookie_login(request): if request.method == 'POST': name = request.POST.get('name') pwd = request.POST.get('pwd') if name == 'wudi' and pwd == '123': obj = redirect('index') obj.set_cookie('is_login',True) obj.set_cookie('name',name) return obj return render(request,'test.html') def index(request): print(request.COOKIES) is_login = request.COOKIES.get('is_login') if is_login: return render(request,'index.html',{'name':name}) else: return redirect('/test_cookie_login')
删除cookie
@login_auth def index(request): name = request.COOKIES.get('name') obj.render(request,'index.html',{'name':name}) obj.delete_cookie('is_login') return obj
需求情形二:设置cookie在装饰器里
def login_auth(func): def inner(request,*args,**kwargs): is_login = request.COOKIES.get('is_login') if is_login: return func(request,*args,**kwargs) else: return redirect('/test_cookie_login/') return inner @login_auth def index(request): name = request.COOKIES.get('name') return render(request,'index.html',{'name':name}) def test_cookie_login(request): if request.method == 'POST': name = request.POST.get('name') pwd = request.POST.get('pwd') if name == 'wudi' and pwd == '123': obj = redirect('index') obj.set_cookie('is_login',True) obj.set_cookie('name',name) return obj return render(request,'test.html')
需求情形三:为了使得已经键入登录index.html但却未登录,登录成功之后直接跳转到index.html,设置cookie里加入URL
def login_auth(func): def inner(request,*args,**kwargs): is_login = request.COOKIES.get('is_login') #为了使得已经键入登录index.html但却未登录,登录成功之后直接跳转到index.html next_url = request.get_full_path() if is_login: return func(request,*args,**kwargs) else: return redirect('/test_cookie_login/?next=%s'%next_url) return inner @login_auth def index(request): name = request.COOKIES.get('name') return render(request,'index.html',{'name':name}) def test_cookie_login(request): if request.method == 'POST': name = request.POST.get('name') pwd = request.POST.get('pwd') # 为了使得已经键入登录index.html但却未登录,登录成功之后直接跳转到index.html url = request.GET.get('next') if name == 'wudi' and pwd == '123': obj = redirect(url) obj.set_cookie('is_login',True) obj.set_cookie('name',name) return obj return render(request,'test.html')