CBV和FBV中用户认证装饰器

作者: 廖马儿 | 来源:发表于2017-08-23 16:15 被阅读5次

    FBV中的示例:

    在views.py中
    
    # 用户认证的装饰器
    def auth(func):
        def inner(request, *args, **kwargs):
            v = request.COOKIES.get('username')
            if not v:
                return redirect('/login/')
    
            return func(request, *args, **kwargs)
    
        return inner
    
    @auth
    def index(request):
        # 获取当前已经登录的用户名
    
        v = request.COOKIES.get('username')
    
        print v
    
        if not v:
            return redirect('/cookie/login/')
    
        return render(request, 'cookie/index.html', {'current_user':v})
    
    

    CBV中的示例

    
    # 方法1
    from django.utils.decorators import method_decorator
    
    class Order(views.View):
    
        @method_decorator(auth)
        def get(self, request):
            pass
        @method_decorator(auth)
        def post(self, request):
            pass
    
    # 方法2
    
    from django.utils.decorators import method_decorator
    
    class Order(views.View):
    
        @method_decorator(auth)
        def dispatch(self, request, *args, **kwargs):
            return super(Order, self).dispatch(request, *args, **kwargs)
    
        def get(self, request):
            pass
        def post(self, request):
            pass
    
    # 方法3
    
    from django.utils.decorators import method_decorator
    
    @method_decorator(auth, name='dispatch')
    class Order(views.View):
    
    
        #def dispatch(self, request, *args, **kwargs):
        #    return super(Order, self).dispatch(request, *args, **kwargs)
    
        def get(self, request):
            pass
        def post(self, request):
            pass
    

    相关文章

      网友评论

        本文标题:CBV和FBV中用户认证装饰器

        本文链接:https://www.haomeiwen.com/subject/godddxtx.html