Python Django Cookie 簡單用法解析
更新時間:2019年08月13日 10:19:55 作者:Sch01aR#
這篇文章主要介紹了Python Django Cookie 簡單用法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
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 函數(shù):
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() 中的第一個參數(shù)為 key,第二個參數(shù)為 value
home 函數(shù):
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 函數(shù):
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 函數(shù):
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 驗證成功

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
jupyter notebook出現(xiàn)In[*]的問題及解決
這篇文章主要介紹了jupyter notebook出現(xiàn)In[*]的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
face++與python實現(xiàn)人臉識別簽到(考勤)功能
這篇文章主要為大家詳細介紹了face++與python實現(xiàn)人臉識別簽到(考勤)功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-08-08
基于Python實現(xiàn)剪切板實時監(jiān)控方法解析
這篇文章主要介紹了基于Python實現(xiàn)剪切板實時監(jiān)控方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-09-09

