Python Django Cookie 简单用法解析

yipeiwu_com5年前Python基础

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 验证成功

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python循环语句之break与continue的用法

Python循环语句之break与continue的用法

Python break 语句 Python break语句,就像在C语言中,打破了最小封闭for或while循环。 break语句用来终止循环语句,即循环条件没有False条件或者序列...

Python简单实现enum功能的方法

本文实例讲述了Python简单实现enum功能的方法。分享给大家供大家参考,具体如下: class Enumerate(object): def __init__(self,na...

python:print格式化输出到文件的实例

遇到一个写文件的小程序,需要把print输出改成输出到文件,遇到这个问题的思路是把需要的字符串拼接到一个字符串中,然后在写到文件中,这样做觉得很麻烦,想到之前的学的exec的使用,但是实...

Python Web框架Flask中使用新浪SAE云存储实例

对于部署在新浪应用引擎SAE上的项目,使用新浪SAE云存储是不错的存储方案。 新浪SAE云存储仅能在SAE环境中正常使用,对它进行简单封装后,可以直接在Flask中使用,项目代码见Git...

python保留小数位的三种实现方法

前言 保留小数位是我们经常会碰到的问题,尤其是刷题过程中。那么在python中保留小数位的方法也非常多,但是笔者的原则就是什么简单用什么,因此这里介绍几种比较简单实用的保留小数位的方法:...