- 类视图使用装饰器
def my_decorator(func): def wrapper(request, *args, **kwargs): print('自定义装饰器被调用了') print('请求路径%s' % request.path) return func(request, *args, **kwargs) return wrapper class DemoView(View): def get(self, request): print('get方法') return HttpResponse('ok') def post(self, request): print('post方法') return HttpResponse('ok')
# 为全部请求方法添加装饰器 @method_decorator(my_decorator, name='dispatch') class DemoView(View): def get(self, request): print('get方法') return HttpResponse('ok') def post(self, request): print('post方法') return HttpResponse('ok') # 为特定请求方法添加装饰器 @method_decorator(my_decorator, name='get') class DemoView(View): def get(self, request): print('get方法') return HttpResponse('ok') def post(self, request): print('post方法') return HttpResponse('ok')
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')
Django—类视图使用装饰器
猜你喜欢
转载自blog.csdn.net/piduocheng0577/article/details/105036977
今日推荐
周排行