首页 > 代码库 > Django基于Cookie装饰器实现用户认证

Django基于Cookie装饰器实现用户认证

def login(request):
    if request.method =="GET":
        return render(request,"login.html")
    elif request.method == "POST":
        u = request.POST.get("user")
        p = request.POST.get("password")
        print(u,p)
        if u ==user and p ==pwd:
            res = redirect("/index")
            res.set_cookie(user,u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
            return res
        else:
            return  render(request,"login.html")
def index(request):
    v = request.COOKIES.get("user")
    if v:
        return render(request,"index.html",{"current_user":v})
    else:
        return redirect("/login")



二, 基于装饰器实现用户认证
FBV:

def auth(func):
    def inner(reqeust,*args,**kwargs):
    v = reqeust.COOKIES.get(user)
    if not v:
      return redirect(/login)
    return func(reqeust, *args,**kwargs)
  return inner

def login(request):
  if request.method =="GET":
    return render(request,"login.html")
  elif request.method == "POST":
    u = request.POST.get("user")
    p = request.POST.get("password")
    if u ==user and p ==pwd:
      res = redirect("/index")
      res.set_cookie(user,u,max_age=5)   #设置cookie,关闭浏览器cookie失效。max_age=5表示5秒后cookie失效,需要重新登录
         return res
    else:
      return  render(request,"login.html")
@auth
def index(request):
  v = request.COOKIES.get("user")
  return render(request,"index.html",{"current_user":v})
  

 

Django基于Cookie装饰器实现用户认证