溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

詳解Django中類視圖使用裝飾器的方式

發(fā)布時(shí)間:2020-09-15 14:42:41 來源:腳本之家 閱讀:138 作者:skaarl 欄目:開發(fā)技術(shù)

類視圖使用裝飾器

為類視圖添加裝飾器,可以使用兩種方法。

為了理解方便,我們先來定義一個(gè)為函數(shù)視圖準(zhǔn)備的裝飾器(在設(shè)計(jì)裝飾器時(shí)基本都以函數(shù)視圖作為考慮的被裝飾對(duì)象),及一個(gè)要被裝飾的類視圖。

def my_decorator(func):
  def wrapper(request, *args, **kwargs):
    print('自定義裝飾器被調(diào)用了')
    print('請(qǐng)求路徑%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()))
]

此種方式最簡(jiǎn)單,但因裝飾行為被放置到了url配置中,單看視圖的時(shí)候無法知道此視圖還被添加了裝飾器,不利于代碼的完整性,不建議使用。

此種方式會(huì)為類視圖中的所有請(qǐng)求方法都加上裝飾器行為(因?yàn)槭窃谝晥D入口處,分發(fā)請(qǐng)求方式前)。

4.2 在類視圖中裝飾

在類視圖中使用為函數(shù)視圖準(zhǔn)備的裝飾器時(shí),不能直接添加裝飾器,需要使用method_decorator將其轉(zhuǎn)換為適用于類視圖方法的裝飾器。

method_decorator裝飾器使用name參數(shù)指明被裝飾的方法

# 為全部請(qǐng)求方法添加裝飾器
@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')


# 為特定請(qǐng)求方法添加裝飾器
@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')

如果需要為類視圖的多個(gè)方法添加裝飾器,但又不是所有的方法(為所有方法添加裝飾器參考上面例子),可以直接在需要添加裝飾器的方法上使用method_decorator,如下所示

from django.utils.decorators import method_decorator

# 為特定請(qǐng)求方法添加裝飾器
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')

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI