您好,登錄后才能下訂單哦!
home.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>個人信息頁面</title> </head> <body> <p>個人信息頁面</p> </body> </html>
只有返回一串字符串
login.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄頁面</title> </head> <body> <p>登錄頁面</p> <form action="/login/" method="post"> {% csrf_token %} <p> 賬號: <input type="text" name="user"> </p> <p> 密碼: <input type="text" name="pwd"> </p> <p> <input type="submit" value="登錄"> </p> </form> </body> </html>
要考慮加上 csrf_token,不然會 403
login 函數:
from django.shortcuts import render, redirect from app01 import models def login(request): if request.method == "POST": username = request.POST.get("user") password = request.POST.get("pwd") if username == "admin" and password == "admin": rep = redirect("/home/") # 得到一個響應對象 rep.set_cookie("login", "success") # 設置 cookie return rep return render(request, "login.html")
set_cookie() 中的第一個參數為 key,第二個參數為 value
home 函數:
from django.shortcuts import render, redirect from app01 import models def home(request): ret = request.COOKIES.get("login") # 獲取 cookie 的 value if ret == "success": # cookie 驗證成功 return render(request, "home.html") else: return redirect("/login/")
輸入賬號、密碼:admin,cookie 驗證成功
給 cookie 加鹽:
login 函數:
from django.shortcuts import render, redirect from app01 import models def login(request): if request.method == "POST": username = request.POST.get("user") password = request.POST.get("pwd") if username == "admin" and password == "admin": rep = redirect("/home/") # 得到一個響應對象 # rep.set_cookie("login", "success") # 設置 cookie rep.set_signed_cookie("login", "success", salt="whoami") # 設置 cookie 并加鹽 return rep return render(request, "login.html")
home 函數:
from django.shortcuts import render, redirect from app01 import models def home(request): # ret = request.COOKIES.get("login") # 獲取 cookie 的 value ret = request.get_signed_cookie("login", salt="whoami") # 獲取加鹽后 cookie 的 value if ret == "success": # cookie 驗證成功 return render(request, "home.html") else: return redirect("/login/")
輸入賬號、密碼:admin,cookie 驗證成功
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。