zoukankan      html  css  js  c++  java
  • django的cookie验证_django

    一、cookie

    cookie:客户端浏览器上的一个文件(类似字典,键值对形式存在),换电脑或者换浏览器都不生效

    1、基于cookie做用户验证

     1 user_info={
     2     "test":{"pwd":"test"},
     3     "chen":{"pwd":"chen"},
     4 
     5 }
     6 def login_test(request):
     7     if request.method=="GET":
     8         return render(request,"index_login.html")
     9     if request.method=="POST":
    10         u=request.POST.get("username")
    11         p=request.POST.get("password")
    12         print(u,p)
    13         if not user_info.get(u):
    14             return render(request,"index_login.html")
    15         if user_info.get(u)["pwd"]==p:
    16             #验证正确,返回cookie和跳转
    17             res=redirect("/index/")
    18             res.set_cookie("username",u)
    19             return res
    20         else:
    21             return redirect("/login_test/")
    22 
    23 def index(request):
    24     v=request.COOKIES.get("username")
    25     if not v:
    26         return redirect("/login_test/")
    27     return render(request,"index.html",{"current_user":v})

    2、cookie的参数

     1 def cookie(request):
     2     #获取cookie
     3     request.COOKIES.get("username")
     4     request.COOKIES["username"]
     5 
     6     #发送cookie到客户端,关闭浏览器失效
     7     u=123
     8     res="redirect('/index/')"
     9     
    10     res.set_cookie("username",u)
    11 
    12 
    13     #其他参数
    14     #设置超时时间:
    15     #超时时间,失效max_age(多少秒之后失效)
    16     res.set_cookie("username", "value",max_age=10)
    17     #超时时间,失效expires(到什么时间点失效)
    18     import datetime
    19     current_date=datetime.datetime.utcnow()
    20     print(current_date)
    21     current_date=current_date+datetime.timedelta(seconds=5)
    22     res.set_cookie("username", "value", expires=current_date) #5秒之后失效
    23 
    24     #path="/" cookie生效的路径,/路径下的可以被所有url访问,如设置/index,只能被/index的url访问
    25 
    26 
    27     return res    

    设置cookie是密文形式:带签名的cookie:

    设置:

    res.set_signed_cookie("username","chen",salt="sdfadf")

    获取:

    request.get_signed_cookie("username",salt="sdfadf")

    3、利用装饰器完成用户验证

    FBV:

    CBV:

    只对其中的一个请求做用户验证:(不能直接加)

    对所有的函数做验证:

  • 相关阅读:
    卡片选项页面 JTabbedPane 的使用
    下拉列表 JComboBox 的使用
    单选按钮 JradioButton 和复选框 JcheckBox 的使用
    标签 JLable 类
    文本区 JTextArea 的使用
    密码框JPasswordField 的使用
    JHDU 2601 An easy problem (数学 )
    HDU 2554 N对数的排列问题 ( 数学 )
    LaTeX初识 新手入门 Texlive和Texmaker学习
    [leetcode-387-First Unique Character in a String]
  • 原文地址:https://www.cnblogs.com/chenxiaozan/p/13065697.html
Copyright © 2011-2022 走看看