• FBV和CBV装饰器


    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
  • 相关阅读:
    Linux下find命令详解
    shell if语句
    目标文件系统映像制作工具mkyaffs2image
    编译内核
    FPS含义
    linux下echo命令详解
    Mssql数据库语句综合
    string 字符串操作
    Lession 15 Good news
    Mysql使作心得(备份,还原,乱码处理)
  • 原文地址:https://www.cnblogs.com/sunhao96/p/8980476.html
Copyright © 2020-2023  润新知