示例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})