Django之Cookie
目录
- Django之Cookie
- 介绍
- Django操作Cookie
- 设置Cookie
- 浏览器查看Cookie
- 获取Cookie
- 设置超时Cookie
- 注销Cookie
- 模拟登录验证
- 登录验证装饰器
- 登录验证装饰器-升级版
介绍
当我们上网使用社交媒体或者购物时,浏览器需要通过一种方式来记住我们。想象一下你进入一家商店,店员会将一张带有身份信息的会员卡片递给你,并让你每次进店时都将卡片带在身上,这张小卡片就是Cookie
Cookie
是由服务器发送到用户的浏览器中的小型文本文件,它存储在用户的计算机上,方便用户每次访问同一个浏览器页面时能够让服务器对其识别
Django操作Cookie
三板斧中的redirect
HttpResponse
render
对象都可以操作Cookie
设置Cookie
def test(request):# response设置为响应对象response = HttpResponse()# 为该对象绑定Cookie并赋值response.set_cookie('name','Paul')# 将有Cookie的响应对象返回给web端return response
浏览器查看Cookie
获取Cookie
def test2(request):my_cookie = request.COOKIES.get('name')print(my_cookie)return HttpResponse('ok')
# 输出:Paul
设置超时Cookie
# 设置超时Cookie
def test(request):response = HttpResponse()response.set_cookie('name', 'Paul',max_age=5)return response# 间隔五秒获取两次Cookie
def test2(request):my_cookie = request.COOKIES.get('name')print(my_cookie)time.sleep(5)print(my_cookie)return HttpResponse('ok')
# 输出:Paul
# None
注销Cookie
def test2(request):# 将浏览器重定向的同时注销Cookieresponse = redirect('home')response.delete_cookie('name')return response
模拟登录验证
def test(request):form_obj = UserForm()user = request.POST.get('user')pwd = request.POST.get('pwd')if user =='123123' and pwd == '123123':response = HttpResponse('登录成功')response.set_cookie('user','123123')return responsereturn render(request,'app01/register.html',locals())def test2(request):response = redirect('home')if request.COOKIES.get('user'):return responsereturn HttpResponse('请先登录')
登录验证装饰器
def check_cookie(func):def inner(request, *args, **kwargs):if request.COOKIES.get('user'):res = func(request, *args, **kwargs)return reselse:return HttpResponse('请先登录')return inner@check_cookie
def test2(request):response = redirect('home')return render(request, 'app01/home.html')
登录验证装饰器-升级版
def login(request):form_obj = UserForm()user = request.POST.get('user')pwd = request.POST.get('pwd')if user == '123123' and pwd == '123123':# 获取Cookie后直接重定向到url中next的路由,如果没有则返回homeresponse = redirect(request.GET.get('next', 'home'))response.set_cookie('user', '123123')return responsereturn render(request, 'app01/register.html', locals())def check_cookie(func):def inner(request, *args, **kwargs):target_url = request.get_full_path()if request.COOKIES.get('user') == '123123':res = func(request, *args, **kwargs)return reselse:return redirect(f'/app01/test/?next={target_url}')return inner@check_cookie
def home(request):return HttpResponse('这里是home界面')