django添加装饰器

引入模块:
from django.utils.decorators import method_decorator


添加:@method_decorator(func)
from django.utils.decorators import method_decorator
def outer(func):
    def inner(request, *args, **kwargs):
        print(request.method)
        return func(request, *args, **kwargs)
    return inner


class Login(views.View):

    @method_decorator(outer)
    def get(self, request, *args, **kwargs):

        return render(request, 'login.html', {'message': ''})





def outer(func):
    def inner(request, *args, **kwargs):
        print(request.method)
        return func(request, *args, **kwargs)
    return inner

========== mark =========

//对所有请求做处理
class Order(views.View):
    pass
# CBV
# @method_decorator(outer, name='dispatch')
class Login(views.View):

    # @method_decorator(outer)
    def dispatch(self, request, *args, **kwargs):
        ret = super(Login, self).dispatch(request, *args, **kwargs)
        return ret

如果对某一类请求做处理,则在相应方法上添加装饰器
如果对所有请求做处理,则在dispatch上添加装饰器


原文地址:https://www.cnblogs.com/jiefangzhe/p/10691942.html