類視圖使用裝飾器
為類視圖添加裝飾器,可以使用兩種方法。
為了理解方便,我們先來定義一個為函數視圖准備的裝飾器(在設計裝飾器時基本都以函數視圖作為考慮的被裝飾對象),及一個要被裝飾的類視圖。
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')
4.1 在URL配置中裝飾
urlpatterns = [ url(r'^demo/$', my_decorate(DemoView.as_view())) ]
此種方式最簡單,但因裝飾行為被放置到了url配置中,單看視圖的時候無法知道此視圖還被添加了裝飾器,不利於代碼的完整性,不建議使用。
此種方式會為類視圖中的所有請求方法都加上裝飾器行為(因為是在視圖入口處,分發請求方式前)。
4.2 在類視圖中裝飾
在類視圖中使用為函數視圖准備的裝飾器時,不能直接添加裝飾器,需要使用method_decorator將其轉換為適用於類視圖方法的裝飾器。
method_decorator裝飾器使用name參數指明被裝飾的方法
# 為全部請求方法添加裝飾器 @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')
如果需要為類視圖的多個方法添加裝飾器,但又不是所有的方法(為所有方法添加裝飾器參考上面例子),可以直接在需要添加裝飾器的方法上使用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')