欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python Django Cookie 簡單用法解析

 更新時間:2019年08月13日 10:19:55   作者:Sch01aR#  
這篇文章主要介紹了Python Django Cookie 簡單用法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

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/") # 得到一個響應(yīng)對象
      rep.set_cookie("login", "success") # 設(shè)置 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 驗(yàn)證成功
    return render(request, "home.html")
  else:
    return redirect("/login/")

輸入賬號、密碼:admin,cookie 驗(yàn)證成功

給 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/") # 得到一個響應(yīng)對象
      # rep.set_cookie("login", "success") # 設(shè)置 cookie
      rep.set_signed_cookie("login", "success", salt="whoami") # 設(shè)置 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 驗(yàn)證成功
    return render(request, "home.html")
  else:
    return redirect("/login/")

輸入賬號、密碼:admin,cookie 驗(yàn)證成功

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論