Cookie和Session版的登錄驗證
阿新 • • 發佈:2018-10-14
action submit user ner ron con render def *args
URL :
from django.conf.urls import url from app01 import views urlpatterns = [ url(r‘^login/‘, views.login), url(r‘^home/‘, views.home), url(r‘^index/‘, views.index), ]
前端 :
<form action="" method="post"> {% csrf_token %} <input type="text" name="name"> <input type="password" name="pwd"> <input type="submit"> </form>
Cookie視圖 :
from django.shortcuts import render,redirect,HttpResponse #裝飾器 def login_required(fn): def inner(request, *args, **kwargs): if request.COOKIES.get("login") != "1": next = request.path_info #未登錄用戶訪問無權限的頁面, 獲取所訪問的url, 以便登陸後直接跳轉 return redirect("/login/?next={}".format(next)) #將所獲取的url參數傳遞到登錄頁面的url上 ret = fn(request, *args, **kwargs) return ret return inner #登錄頁面 def login(request): if request.method == "POST": user = request.POST.get("name") pwd= request.POST.get("pwd") if user == "dong" and pwd == "dong": next = request.GET.get("next") #在登陸頁面的url上獲取未登錄用戶訪問無權限頁面所傳遞的參數 if next: #如果有參數 ret = redirect(next) else: #沒有參數 ret = redirect("/home/") #沒有參數說明用戶未訪問無權限頁面,直接登錄 ret.set_cookie("login", "1") return ret return render(request, "login.html") @login_required def home(request): return HttpResponse("home頁面") @login_required def index(request): return HttpResponse("index")
Session視圖 :
#裝飾器 def login_required(fn): def inner(request, *args, **kwargs): if request.Session.get("login") != "1": next = request.path_info #未登錄用戶訪問無權限的頁面, 獲取所訪問的url, 以便登陸後直接跳轉 return redirect("/login/?next={}".format(next)) #將所獲取的url參數傳遞到登錄頁面的url上 ret = fn(request, *args, **kwargs) return ret return inner #登錄頁面 def login(request): if request.method == "POST": user = request.POST.get("name") pwd = request.POST.get("pwd") if user == "dong" and pwd == "dong": request.session["login"] = "1" #設置session,自動傳遞 next = request.GET.get("next") #在登陸頁面的url上獲取未登錄用戶訪問無權限頁面所傳遞的參數 if next: #如果有參數 return redirect(next) else: #沒有參數 return redirect("/home/") #沒有參數說明用戶未訪問無權限頁面,直接登錄 # ret.set_cookie("login", "1") # return ret return render(request, "login.html") @login_required def home(request): return HttpResponse("home頁面") @login_required def index(request): return HttpResponse("index")
Cookie和Session版的登錄驗證