一、基于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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/186260.html
標籤:其他
