欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2018年08月12日 08:43:20   作者:skaarl  
這篇文章主要介紹了詳解Django中類視圖使用裝飾器的方式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

類視圖使用裝飾器

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

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

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配置中,單看視圖的時候無法知道此視圖還被添加了裝飾器,不利于代碼的完整性,不建議使用。

此種方式會為類視圖中的所有請求方法都加上裝飾器行為(因為是在視圖入口處,分發(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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論