django 視圖 分為兩種:
1. FBV 基於函數的視圖 function based view
2. CBV 基於類的視圖 class based view
基於類的視圖
CBV :基於 類的視圖函數
1、后端邏輯處理時不用通過邏輯,來判斷請求方式是get還是post請求
在視圖類中,定義了get方法就是寫get請求的邏輯,定義類post方法時
就是post請求邏輯。
2、View 的源碼分析過程
1.先從url.py 文件的開始分析入手:
1 from app01 import views 2 3 urlpatterns = [ 4 path('admin/', admin.site.urls), 5 6 path('login/', views.LoginView.as_view()), # CBV 基於類的視圖 7 path('index/', views.index), # FBV 基於函數的視圖 8 ] 9 10 1. #views.LoginView.as_view() 必須是一個視圖函數
2. 點擊進入源碼
View 大致執行流程:
self.as_view() =====> self.dispatch() ====> self.get/post/等
# 路由分發開始 獲取具體的請求方面名,在通過反射具體的請求函數 視圖函數
1 class View: 2 3 http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] 4 5 6 def as_view(cls, **initkwargs): 7 8 def view(request, *args, **kwargs): 9 10 11 return self.dispatch(request, *args, **kwargs)
return view 12 13 14 def dispatch(self, request, *args, **kwargs): 15 16 # self.http_method_names=['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] 17 18 if request.method.lower() in self.http_method_names: 19 # 用反射 獲取函數 request.method.lower() # 為 get 20 handler = getattr(self, request.method.lower(), self.http_method_not_allowed) 21 # hander=getattr(self,"get") # 相當於執行了 該類下的get方法 22 else: 23 handler = self.http_method_not_allowed 24 25 #handler(request, *args, **kwargs) ====> get(request,*args, **kwargs) 26 27 return handler(request, *args, **kwargs) # 相當於類下的 執行 return self.get(request,)
3. 在view.py 文件中:
1 from django.view import View 2 3 # CBV 基於類的視圖 4 class LoginView(View): 5 6 def get(self,request,*args, **kwargs): 7 8 9 return render(request,"login.html") 10 11 def post(self,request,*args, **kwargs): 12 13 return redirect('/index/') 14 15 16 # FBV 基於函數的視圖 17 def index(request): 18 19 return render(request,"index.html")