zoukankan      html  css  js  c++  java
  • django之基于cookie和装饰器实现用户认证

    示例1

     1 # Create your views here.
     2 user = "a"
     3 pwd = "a"
     4 def login(request):
     5     if request.method =="GET":
     6         return render(request,"login.html")
     7     elif request.method == "POST":
     8         u = request.POST.get("user")
     9         p = request.POST.get("password")
    10         print(u)
    11         print(p)
    12         if u ==user and p ==pwd:
    13             res = redirect("/index")
    14             res.set_cookie('user',u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
    15             return res
    16         else:
    17             return  render(request,"login.html")
    18 def index(request):
    19     v = request.COOKIES.get("user")
    20     if v:
    21         return render(request,"index.html",{"current_user":v})
    22     else:
    23         return redirect("/login")

    示例2   ---   基于装饰器实现用户认证

     1 user = "a"
     2 pwd = "a"
     3 
     4 def auth(func):
     5     def inner(reqeust,*args,**kwargs):
     6         v = reqeust.COOKIES.get('user')
     7         if not v:
     8             return redirect('/login')
     9         return func(reqeust, *args,**kwargs)
    10     return inner
    11 
    12 def login(request):
    13     if request.method =="GET":
    14         return render(request,"login.html")
    15     elif request.method == "POST":
    16         u = request.POST.get("user")
    17         p = request.POST.get("password")
    18         if u ==user and p ==pwd:
    19             res = redirect("/index")
    20             res.set_cookie('user',u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
    21             return res
    22         else:
    23             return  render(request,"login.html")
    24 @auth
    25 def index(request):
    26     v = request.COOKIES.get("user")
    27     return render(request,"index.html",{"current_user":v})
  • 相关阅读:
    Unity之图片压缩,批量设置,导入自动设置
    Unity之可寻址资源之初始化,下载
    最优二叉树
    独立任务最优调度问题
    石子合并问题
    linux初学笔记
    码农
    用循环打印出多种三角形
    人机猜拳(这是最近的一个总结)
    期末总结
  • 原文地址:https://www.cnblogs.com/liruixin/p/6271330.html
Copyright © 2011-2022 走看看