码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-07 12:30:17      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:span   dex   关闭   use   浏览器   end   return   eth   pre   

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装饰器实现用户认证

标签:span   dex   关闭   use   浏览器   end   return   eth   pre   

原文地址:http://www.cnblogs.com/ixiaosong/p/6955999.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!