一、什么是FBV&CBV
FBV -Function Base VIew
CBV-Class Base Viev
字面理解就是view層基于方法編寫邏輯,和基于類編寫邏輯~
這個是java 差別很大,java一直遵循這面向對象編程,但python 的強大就是既能面向函數,也能面向對象這就因此出現了FBV 和CBV
二、如何寫FBV&CBV
我更愿意把FBV中的F,理解成def 中的f,我在簡書之前的例子就是典型的FBV
image.png
CBV 我們需要 寫的類繼承from django.views import View
from django.views import View
class Test(View):
def get(self,request):
return redirect('http://www.baidu.com')
#備注 也可以繼承dispatch方法
class test(View):
def dispatch(self, request, *args, **kwargs):
data = super(test,self).dispatch(request, *args, **kwargs)
return data
def get(self,request):
return redirect('http://www.baidu.com')
因為技術有限,我是個初學者,通過源碼看了下源碼只能猜出個大概,我們看一下源碼,源碼里面有個方法dispatch,中文的意思就是派遣調度
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)
我們來翻一下這段,先是進行判斷請求的方法是否包含在self.http_method_names 里面,我們在看一下源碼中的http_method_names
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
image.png
源碼中http_method_names是一個集合,里面包含著網頁的八中請求方式,也就是當從網頁請求頭接收到的方法是這八個其中之一的,但具體是怎么反射的可以去看下源碼,我技術有限也看不懂只能猜出個大概,但還有點說不通,以后看懂了在詳細說吧。
當使用CBV的時候urls 地址映射關系寫法也有少許改動
image.png
也就類名.as_view方法