FBV(function base views) 就是在視圖裏使用函數處理請求。html
CBV(class base views) 就是在視圖裏使用類處理請求。前端
Python是一個面向對象的編程語言,若是隻用函數來開發,有不少面向對象的優勢就錯失了(繼承、封裝、多態)。因此Django在後來加入了Class-Based-View。可讓咱們用類寫View。這樣作的優勢主要下面兩種:python
用函數寫的話以下所示:django
from django.http import HttpResponse def my_view(request): if request.method == 'GET': return HttpResponse('OK')
用class-based view寫的話以下所示:編程
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異常。app
在url中,寫法以下:編程語言
# urls.py from django.conf.urls import url from myapp.views import MyView urlpatterns = [ url(r'^index/$', MyView.as_view()), ]
類的屬性能夠經過兩種方法設置,第一種是常見的python的方法,能夠被子類覆蓋:ide
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中設置類的屬性Pythonpost
urlpatterns = [ url(r'^index/$', GreetingView.as_view(name="egon")), ]
要理解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寫在左邊。
更多參考:https://www.cnblogs.com/yuanchenqi/articles/8715364.html
########### urls.py from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.LoginView.as_view()), ] ############views.py from django.shortcuts import render, HttpResponse from django.views import View class LoginView(View): def get(self, request): return render(request, "login.html") def post(self, request): return HttpResponse("post...") def put(self, request): pass
構建login.html頁面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <input type="submit"> </form> </body> </html>
注意:
(1)CBV的本質仍是一個FBV
(2)url中設置類的屬性Python:
path('login/', views.LoginView.as_view()),
用戶訪問login,views.LoginView.as_view()必定是一個函數名,不是函數調用。
(3)頁面效果
點擊提交post請求:
class View: """ get:查 post:提交,添加 put:全部內容都更新 patch:只更新一部分 delete:刪除 """ http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value) @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 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) def http_method_not_allowed(self, request, *args, **kwargs): logger.warning( 'Method Not Allowed (%s): %s', request.method, request.path, extra={'status_code': 405, 'request': request} ) return HttpResponseNotAllowed(self._allowed_methods()) def options(self, request, *args, **kwargs): """Handle responding to requests for the OPTIONS HTTP verb.""" response = HttpResponse() response['Allow'] = ', '.join(self._allowed_methods()) response['Content-Length'] = '0' return response def _allowed_methods(self): return [m.upper() for m in self.http_method_names if hasattr(self, m)]
注意:
as_view是一個類方法,所以views.LoginView.as_view()須要添加(),這樣才調用這個類方法。
as_view執行完,返回是view(函數名)。所以login一旦被用戶訪問,真正被執行是view函數。
view函數的返回值:
return self.dispatch(request, *args, **kwargs)
這裏的self是誰取決於view函數是誰調用的。view——》as_view——》LoginView(View的子類)。在子類沒有定義dispatch的狀況下,調用父類的。
self.dispatch(request, *args, **kwargs)是執行dispatch函數。因而可知login訪問,真正被執行的是dispatch方法。且返回結果是dispatch的返回結果,且一路回傳到頁面顯示。用戶看的頁面是什麼,徹底由self.dispatch決定。
request.method.lower():此次請求的請求方式小寫。
self.http_method_names:['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
判斷請求方式是否在這個請求方式列表中。
handler就是反射獲得的實例方法get,若是找不到則經過http_method_not_allowed返回報錯。
from django.shortcuts import render, HttpResponse from django.views import View class LoginView(View): def dispatch(self, request, *args, **kwargs): print("dispath...") # return HttpResponse("自定義") # 兩種寫法 # ret = super(LoginView, self).dispatch(request, *args, **kwargs) # ret = super().dispatch(request, *args, **kwargs) # return ret def get(self, request): print("get.....") return render(request, "login.html") def post(self, request): print("post....") return HttpResponse("post...") def put(self, request): pass
注意:有兩種繼承父類dispatch方法的方式:
ret = super(LoginView, self).dispatch(request, *args, **kwargs) ret = super().dispatch(request, *args, **kwargs)
谷歌的一個插件,模擬前端發get post put delete請求,下載,安裝。https://www.getpostman.com/apps