首页 > 代码库 > 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装饰器实现用户认证
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。