
FBV装饰器:
def cook(request): err_msg=""
if request.method == "GET":
return render(request,'cookie.html') if request.method == "POST": username = request.POST.get('username')
p = request.POST.get('password') dic = user_info.get(username)
print(dic) if not dic:
err_msg="用户不存在"
return render(request,'cookie.html',{'err_msg':err_msg}) if dic['pwd'] == int(p): res = redirect('/xiaoqing/cookie1')
# res.set_cookie('username_cookie',username) #设置cookie 关闭浏览器失效
# res.set_cookie('username_cookie',username,max_age=10) 设置cookie失效时间 10秒过期
import datetime
current_date=datetime.datetime.utcnow()
change_date=current_date+datetime.timedelta(seconds=5)
res.set_cookie('username_cookie',username,expires=change_date) #到哪个时间失效 # res.set_signed_cookie('username_cookie',username,salt='sdasdas') return res
else:
return render(request,'cookie.html')
cook函数set cookie
def auth(func): #装饰器 cookie认证 def inner(request,*args,**kwargs):
v = request.COOKIES.get('username_cookie')
print(v)
if not v:
return redirect('/xiaoqing/cookie') return func(request,*args,**kwargs) return inner @auth
def cook1(request):
#获取当前已经登录的用户 v=request.COOKIES.get('username_cookie') #获取cookie
# 或者 v=request.COOKIES['username_cookie'] #获取cookie # v=request.get_signed_cookie('username_cookie',salt='sdasdas') #获取加密cookie return render(request,'cookie1.html',{'current_user':v,})
CBV装饰器
def auth(func): #装饰器 def inner(request,*args,**kwargs):
v = request.COOKIES.get('username_cookie')
print(v)
if not v:
return redirect('/xiaoqing/cookie') return func(request,*args,**kwargs) return inner from django import views from django.utils.decorators import method_decorator #导入方法 @method_decorator(auth,name='dispatch') #类中全部方法做认证
class Order(views.View): # @method_decorator(auth) #单独方法做认证
def get(self,request):
v=request.COOKIES.get('username_cookie') return render(request,'cookie1.html',{'current_user':v,}) def post(self,request):
pass