Django——基于cookie的登录认证 CBV加装饰器
一、基于cookie的登录认证
urls.py
from django.urls import path from app01 import views urlpatterns = [ # cookie版登录 path('login/', views.login), path('order/', views.order), path('logout/', views.logout), path('userinfo/', views.userinfo), ]
#有3个页面 (登录,内容,用户信息)
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> <p>用户名:<input type="text" name="name"></p> <p>密码:<input type="password" name="password"></p> <p><input type="submit" value="提交"></p> </form> </body> </html>
order.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/logout/">点我退出</a> </body> </html>
userinfo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户信息页面</h1> </body> </html>
views.py
from django.shortcuts import render, HttpResponse, redirect ## 登录认证装饰器 def login_auth(func): def inner(request, *args, **kwargs): # 登录校验 name = request.COOKIES.get('name') if name: res = func(request, *args, **kwargs) return res else: path = request.get_full_path() return redirect('/login/?returnUrl=%s' % path) #之前的页面 return inner ### cookie版登录 def login(request): if request.method == 'GET': return render(request, 'login.html') else: name = request.POST.get('name') password = request.POST.get('password') if name == 'lqz' and password == '123': # 写入cookie # 登录成功,重定向 path = request.GET.get('returnUrl') if path: obj = redirect(path) else: obj = redirect('/index/') #或者重定性到其他页面 obj.set_cookie('name', name) return obj else: return HttpResponse('用户名或密码错误') # def order(request): # name = request.COOKIES.get('name') # if name: # return render(request,'order.html') # else: # return redirect('/login') ## 装饰器版本(只要加了装饰器,一旦进入这个视图函数,就表明登录成功了) @login_auth def order(request): return render(request, 'order.html') @login_auth def userinfo(request): return render(request, 'userinfo.html') def logout(request): obj = HttpResponse('退出登录成功') obj.delete_cookie('name') return obj
views.py中 logout函数为啥不用ajax ?
如果用ajax发请求,只能返回页面或json格式数据,这个响应是ajax接收到的而不是浏览器,数据也都在ajax里,
需要手动把cookie删除,ajax是删除不掉的。(收麻烦,删麻烦)
另外用ajax发请求,需要手动把cookie拼在ajax请求头里再发,很麻烦。(发麻烦)
二、CBV加装饰器
在上面登录认证功能的基础上,如果要变成类
views.py需要加上
from django.views import View from django.utils.decorators import method_decorator # 使用登录认证装饰器 # 用法一 # @method_decorator(login_auth,name='get') #给get函数加上login_auth装饰器 # @method_decorator(login_auth,name='post')#如果是post那就写post class UserInfo(View): def get(self, request, *args, **kwargs): return HttpResponse('userinfo get') #方法二 class UserInfo(View): # 装饰器加这里 @method_decorator(login_auth) def get(self, request, *args, **kwargs): return HttpResponse('userinfo get') # 总结:两种用法 -加在类上:@method_decorator(login_auth,name='get') -加载方法上:@method_decorator(login_auth)