CBV和FBV中用户认证装饰器

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
    原文作者:廖马儿
    原文地址: https://www.jianshu.com/p/b8995494a16f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞