1.什么是FBV和CBV
FBV是指視圖函式以普通函式的形式;CBV是指視圖函式以類的方式,
2.普通FBV形式
def index(request):
return HttpResponse('index')
3.CBV形式
3.1 CBV形式的路由
path(r'^login/',views.MyLogin.as_view())
3.2 CBV形式的視圖函式
from django.views import View
class MyLogin(View):
def get(self,request): #get請求時執行的函式
return render(request,'form.html')
def post(self,request): #post請求時執行的函式
return HttpResponse('post方法')
FBV和CBV各有千秋
CBV特點是:
能夠直接根據請求方式的不同直接匹配到對應的方法執行
4.CBV原始碼分析
核心在于路由層的views.MyLogin.as_view()--->其實呼叫了as_view()函式就等于呼叫了CBV里面的view()函式,因為as_view()函式是一個閉包函式,回傳的是view---->view函式里面回傳了dispatch函式--->dispatch函式會根據請求的方式呼叫對應的函式!
5.CBV添加裝飾器的三種方式
from django.views import View #CBV需要引入的模塊
from django.utils.decorators import method_decorator #加裝飾器需要引入的模塊
"""
CBV中django不建議你直接給類的方法加裝飾器
無論該裝飾器是否能都正常作業 都不建議直接加
"""
django給CBV提供了三種方法加裝飾器
# @method_decorator(login_auth,name='get') # 方式2(可以添加多個針對不同的方法加不同的裝飾器)
# @method_decorator(login_auth,name='post')
class MyLogin(View):
@method_decorator(login_auth) # 方式3:它會直接作用于當前類里面的所有的方法
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request,*args,**kwargs)
# @method_decorator(login_auth) # 方式1:指名道姓,直接在方法上加login_auth為裝飾器名稱
def get(self,request):
return HttpResponse("get請求")
def post(self,request):
return HttpResponse('post請求')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/501858.html
標籤:其他
