zoukankan      html  css  js  c++  java
  • Django-website 程序案例系列-11 验证装饰器

    FBV装饰器:

    def auth(func):     #装饰器函数
        def inner(request, *args, **kwargs):
            v = request.COOKIES.get('username')
            if not v:
                return redirect('/log/')
            return func(request, *args, **kwargs)
        return inner
    

      

    使用方法:

    在函数上加上@auth

    CBV装饰器:

    第一种方式:利用django自带的工具

    def auth(func):         #装饰器函数  对cookie进行认证
        def inner(request, *args, **kwargs):
            v = request.COOKIES.get('username')
            if not v:
                return redirect('/log/')
            return func(request, *args, **kwargs)
        return inner
    
    from django import views    
    from django.utils.decorators import method_decorator  #导入django自带的工具
    class Auth(views.View):
    
        @method_decorator(auth)  #利用django自带工具 导入认证函数装饰器进行认证,灵活的放在任意需要认证的函数下面
        def get(self, request):
            v = request.COOKIES.get('username')
            return render(request, 'user_list.html', {'current_user': v})
    
        def post(self, request):
            v = request.COOKIES.get('username')
            return render(request, 'user_list.html', {'current_user': v})
    

      

    第二种方式:

    from django import views
    from django.utils.decorators import method_decorator
    class Auth(views.View):
    
        @method_decorator(auth)     #将装饰器放在父类方法上 这样该类下所有方法都被装饰上了装饰器,不用一一在写在函数上面
        def dispatch(self, request, *args, **kwargs):
            return super(Auth, self).dispatch(self, request, *args, **kwargs)
    
        def get(self, request):
            v = request.COOKIES.get('username')
            return render(request, 'user_list.html', {'current_user': v})
    
        def post(self, request):
            v = request.COOKIES.get('username')
            return render(request, 'user_list.html', {'current_user': v})
    

      

    第三种方式:

    from django import views
    from django.utils.decorators import method_decorator
    
    @method_decorator(auth, name='dispatch')  #将装饰器直接装饰在类上面,在用name指定装饰在父类的diapatch方法上,这样也就实现了类里面所有方法的装饰效果
    class Auth(views.View):
    
        def get(self, request):
            v = request.COOKIES.get('username')
            return render(request, 'user_list.html', {'current_user': v})
    
        def post(self, request):
            v = request.COOKIES.get('username')
            return render(request, 'user_list.html', {'current_user': v})
    

      

  • 相关阅读:
    设计规范理解
    JVM读书笔记
    springboot整合RabbitMQ
    springboot 整合Redis
    tomcat原理
    配置嵌入式Servlet容器
    Springboot自动配置原理
    Springboot启动原理
    Springboot配置文件加载顺序
    修改VisualSVN Server地址为ip地址,修改svn服务端地址为ip或者域名地址的方法
  • 原文地址:https://www.cnblogs.com/kuku0223/p/7923187.html
Copyright © 2011-2022 走看看