關於FBV和CBV的使用在以前有提到,點擊穿越。html
首先在視圖中建立一個類並繼承 django.views.View 類,在類中可定義各類請求方式對應執行的函數(函數名爲請求方式名稱小寫)。django
1 from django.views import View 2 3 4 class TestView(View): 5 def get(self, request): 6 return HttpResponse('get') 7 8 def post(self, request): 9 return HttpResponse('post')
配置路由。app
1 from django.conf.urls import url 2 from app import views 3 urlpatterns = [ 4 url(r'^test/', views.TestView.as_view()), 5 ]
作好上述準備以後,就能夠經過相應的請求方法請求對應路由地址來執行CBV視圖中對應請求方法名的函數,爲何Django能幫咱們作到這一點呢?咱們知道,在使用FBV時,路由地址對應的是一個函數句柄,而在CBV中,路由地址對應的是視圖類的 as_view 函數的執行結果。例如:函數
1 from django.conf.urls import url 2 from app import views 3 4 def test(): 5 pass 6 7 urlpatterns = [ 8 url(r'^test_FBV/', test), 9 url(r'^test_CBV/', views.TestView.as_view()), 10 ]
因此從這裏就能夠看出, as_view 函數的返回值必定也是一個函數句柄。查看as_view()函數源碼:post
1 class View(object): 2 3 @classonlymethod 4 def as_view(cls, **initkwargs): 5 for key in initkwargs: 6 if key in cls.http_method_names: 7 raise TypeError("You tried to pass in the %s method name as a " 8 "keyword argument to %s(). Don't do that." 9 % (key, cls.__name__)) 10 if not hasattr(cls, key): 11 raise TypeError("%s() received an invalid keyword %r. as_view " 12 "only accepts arguments that are already " 13 "attributes of the class." % (cls.__name__, key)) 14 15 def view(request, *args, **kwargs): 16 self = cls(**initkwargs) 17 if hasattr(self, 'get') and not hasattr(self, 'head'): 18 self.head = self.get 19 self.request = request 20 self.args = args 21 self.kwargs = kwargs 22 return self.dispatch(request, *args, **kwargs) 23 view.view_class = cls 24 view.view_initkwargs = initkwargs 25 26 update_wrapper(view, cls, updated=()) 27 28 update_wrapper(view, cls.dispatch, assigned=()) 29 return view
直接看 29 行, as_view 函數的返回值其實就是 15 行定義的 view 函數。也就是說當請求對應地址時,實際上執行的是這個 view 函數,url
從 17 、 18 行能夠看出,當咱們在視圖類中定義了 get 函數而沒有定義 head 函數時,就定義一個 head 函數指向了 get 函數。也就是說當只定義了 get 函數而以 head 方式請求時,會執行 get 函數。spa
再看 22 行, view 函數的返回值實際上是 dispatch 函數的執行結果,看源碼:code
1 class View(object): 2 http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] 3 def dispatch(self, request, *args, **kwargs): 4 if request.method.lower() in self.http_method_names: 5 handler = getattr(self, request.method.lower(), self.http_method_not_allowed) 6 else: 7 handler = self.http_method_not_allowed 8 return handler(request, *args, **kwargs)
咱們會發現,dispatch方法很簡單,就是判斷當前請求方法名稱是否包含在 http_method_names 這個列表中。若是包含,則經過 getattr 從當前視圖類實例中獲取該方法名稱函數句柄賦值給 handler ,最後執行。也就是說若是請求方式爲 put ,就會調用視圖類中的 put 函數;若是請求方式爲 patch ,就會調用視圖類中的 patch 函數。htm