FBV
FBV(function base views) 就是在視圖裏使用函數處理請求。html
在以前django的學習中,咱們一直使用的是這種方式,因此再也不贅述。python
CBV
CBV(class base views) 就是在視圖裏使用類處理請求。django
Python是一個面向對象的編程語言,若是隻用函數來開發,有不少面向對象的優勢就錯失了(繼承、封裝、多態)。因此Django在後來加入了Class-Based-View。可讓咱們用類寫View。這樣作的優勢主要下面兩種:編程
- 提升了代碼的複用性,可使用面嚮對象的技術,好比Mixin(多繼承)
- 能夠用不一樣的函數針對不一樣的HTTP方法處理,而不是經過不少if判斷,提升代碼可讀性
使用class-based views
若是咱們要寫一個處理GET方法的view,用函數寫的話是下面這樣服務器
from django.http import HttpResponse def my_view(request): if request.method == 'GET': return HttpResponse('OK')
若是用class-based view寫的話,就是下面這樣app
from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request): return HttpResponse('OK')
Django的url是將一個請求分配給可調用的函數的,而不是一個class。針對這個問題,class-based view提供了一個as_view()
靜態方法(也就是類方法),調用這個方法,會建立一個類的實例,而後經過實例調用dispatch()
方法,dispatch()
方法會根據request的method的不一樣調用相應的方法來處理request(如get()
, post()
等)。到這裏,這些方法和function-based view差很少了,要接收request,獲得一個response返回。若是方法沒有定義,會拋出HttpResponseNotAllowed異常。編程語言
在url中,就這麼寫:ide
# urls.py from django.conf.urls import url from myapp.views import MyView urlpatterns = [ url(r'^index/$', MyView.as_view()), ]
咱們能夠看看as_view這個方法的源碼函數
@classonlymethod def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view
能夠看到as_view最終的執行結果就是返回了一個view函數,而在url中其實咱們就是在調用這個函數,這個函數先是實例化出了一個View類的對象,最後返回的是這個對象的dispatch方法的執行結果post
那麼這個dispatche方法又幹了什麼呢
def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs)
這個方法其實就是判斷咱們的請求方法,並根據請求方法執行相應的方法對應的函數
類的屬性能夠經過兩種方法設置,第一種是常見的Python的方法,能夠被子類覆蓋
from django.http import HttpResponse from django.views import View class GreetingView(View): name = "yuan" def get(self, request): return HttpResponse(self.name) # You can override that in a subclass class MorningGreetingView(GreetingView): name= "alex"
第二種方法,你也能夠在url中指定類的屬性:
在url中設置類的屬性Python
urlpatterns = [ url(r'^index/$', GreetingView.as_view(name="egon")), ]
使用Mixin
我以爲要理解django的class-based-view(如下簡稱cbv),首先要明白django引入cbv的目的是什麼。在django1.3以前,generic view也就是所謂的通用視圖,使用的是function-based-view(fbv),亦即基於函數的視圖。有人認爲fbv比cbv更pythonic,竊覺得否則。python的一大重要的特性就是面向對象。而cbv更能體現python的面向對象。cbv是經過class的方式來實現視圖方法的。class相對於function,更能利用多態的特定,所以更容易從宏觀層面上將項目內的比較通用的功能抽象出來。關於多態,很少解釋,有興趣的同窗本身Google。總之能夠理解爲一個東西具備多種形態(的特性)。cbv的實現原理經過看django的源碼就很容易明白,大致就是由url路由到這個cbv以後,經過cbv內部的dispatch方法進行分發,將get請求分發給cbv.get方法處理,將post請求分發給cbv.post方法處理,其餘方法相似。怎麼利用多態呢?cbv裏引入了mixin的概念。Mixin就是寫好了的一些基礎類,而後經過不一樣的Mixin組合成爲最終想要的類。
因此,理解cbv的基礎是,理解Mixin。Django中使用Mixin來重用代碼,一個View Class能夠繼承多個Mixin,可是隻能繼承一個View(包括View的子類),推薦把View寫在最右邊,多個Mixin寫在左邊。
關於csrf_token的裝飾器
咱們知道當咱們向django發送post請求時,有一箇中間件會檢驗csrf_token,若是咱們不想使用它能夠將它註釋,一樣咱們也能夠經過裝飾器來避免發送POST請求時被服務器拒絕
from django.shortcuts import render, HttpResponse from django.views import View # Create your views here. from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator @csrf_exempt # 避免csrf驗證 def foo(request): return HttpResponse("foo") # 方式1 # @method_decorator(csrf_exempt, name="dispatch") class IndexView(View): # 方式2 @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): print("hello world") # 執行父類的dispatch方法 res = super(IndexView, self).dispatch(request, *args, **kwargs) return res def get(self, request, *args, **kwargs): return HttpResponse("index") def post(self, request, *args, **kwargs): return HttpResponse("post index") def delete(self, request): return HttpResponse("delete index")
能夠看到FBV和CBV的形式均可以經過裝飾器的形式來實現,還有一個csrf_protect是能夠在中間件被註釋時也能夠進行驗證