method_decorator的作用以及使用方法

为Django类视图添加装饰器

在类视图中使用为函数视图准备的装饰器时,不能直接添加装饰器,需要使用method_decorator将其转换为适用于类视图方法的装饰器。

method_decorator装饰器使用name参数指明被装饰的方法

第一种添加装饰器的方法

# 在想要加装饰器的类的 应用中 
# views.py
def my_decorator(view_func):
    """定义装饰器"""
    def wrapper(request, *args, **kwargs):
        print("装饰器被调用了")
		return view_func(request, *args, **kwargs)
    return warpper
class DemoView(View):
    def get(request):
        return HttpResponse("get请求")

    def post(request):
        return HttpResponse("pose请求")
# url.py

url(r'^demo/$', views.my_decorator(view.DemoView.as_view()))

第二种添加装饰器的方法

# views.py
def my_decorator(view_func):
    """定义装饰器"""
    def wrapper(request, *args, **kwargs):
        print("装饰器被调用了")
		return view_func(request, *args, **kwargs)
    return warpper

# 为全部请求方法添加装饰器
# method_decorator的作用是为函数视图装饰器补充第一个self参数,以适配类视图方法。
@method_decorator(my_decorator, name='dispatch')
class DemoView(View):
    def get(self, request):
        return HttpResponse("get请求")

    def post(self, request):
        return HttpResponse("pose请求")


# 为特定请求方法添加装饰器
@method_decorator(my_decorator, name='get')
class DemoView(View):
    def get(self, request):
        return HttpResponse("get请求")

    def post(self, request):
        return HttpResponse("pose请求")

# urls
url(r'^demo/$', view.DemoView.as_view())

第三种添加装饰器的方法

如果需要为类视图的多个方法添加装饰器,但又不是所有的方法(为所有方法添加装饰器参考上面例子),也可以直接在需要添加装饰器的方法上使用method_decorator(就是为指定方法添加装饰器),如下所示:

from django.utils.decorators import method_decorator

# 为特定请求方法添加装饰器
class DemoView(View):

    @method_decorator(my_decorator)  # 为get方法添加了装饰器
    def get(self, request):
        print('get方法')
        return HttpResponse('ok')

    @method_decorator(my_decorator)  # 为post方法添加了装饰器
    def post(self, request):
        print('post方法')
        return HttpResponse('ok')

    def put(self, request):  # 没有为put方法添加装饰器
        print('put方法')
        return HttpResponse('ok')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

itLaity

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值