詳解Django中類視圖使用裝飾器的方式
類視圖使用裝飾器
為類視圖添加裝飾器,可以使用兩種方法。
為了理解方便,我們先來定義一個為函數(shù)視圖準備的裝飾器(在設計裝飾器時基本都以函數(shù)視圖作為考慮的被裝飾對象),及一個要被裝飾的類視圖。
def my_decorator(func):
def wrapper(request, *args, **kwargs):
print('自定義裝飾器被調(diào)用了')
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配置中,單看視圖的時候無法知道此視圖還被添加了裝飾器,不利于代碼的完整性,不建議使用。
此種方式會為類視圖中的所有請求方法都加上裝飾器行為(因為是在視圖入口處,分發(fā)請求方式前)。
4.2 在類視圖中裝飾
在類視圖中使用為函數(shù)視圖準備的裝飾器時,不能直接添加裝飾器,需要使用method_decorator將其轉換為適用于類視圖方法的裝飾器。
method_decorator裝飾器使用name參數(shù)指明被裝飾的方法
# 為全部請求方法添加裝飾器
@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')
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
PyTorch實現(xiàn)聯(lián)邦學習的基本算法FedAvg
這篇文章主要為大家介紹了PyTorch實現(xiàn)聯(lián)邦學習的基本算法FedAvg,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
PyCharm 2020.2下配置Anaconda環(huán)境的方法步驟
這篇文章主要介紹了PyCharm 2020.2下配置Anaconda環(huán)境的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09

