Django fbv 和 cbv 簡述

前面學習的例子都是經過 url 來匹配 一個函數,這種方式叫作 function based view (BSV)。一個典型的使用方式就是經過在view.py裏面定義一個函數,而後經過函數的request參數獲取method的類型,好比直接刷新頁面就是get方式,提交表單就是post方式,這樣來根據提交的不一樣方式進行不一樣的處理。html

好比:python

def user_info(request):
    if request.method == "GET":
        user_list = models.UserInfo.objects.all()
        group_list = models.UserGroup.objects.all()
        return render(request, 'user_info.html', {'user_list': user_list, "group_list": group_list})
    elif request.method == 'POST':
        u = request.POST.get('user')
        p = request.POST.get('pwd')
        models.UserInfo.objects.create(username=u,password=p)
        return redirect('/cmdb/user_info/')

  

另一種方式叫作 class based view (CBV)。這種方式須要導入一個View類,經過自定義一個子類繼承這個類,咱們能夠利用View裏面的dispatch()方法來判斷請求是get仍是post。dispatch方法的本質是一個反射器,能夠根據名字來調用同名的方法。django


View類的部分代碼能夠看出dispatch經過反射獲取列表裏面的方法名稱app

  http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
  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)


CBV的例子以下。ide


注意這裏在子類裏面從新定義了dispatch這個方法,同時又使用了super()來調用父類的構造方法,這樣的好處是功能不變,可是能夠靈活的添加新的功能。函數

from django.views import View
class Home(View):
    def dispatch(self, request, *args, **kwargs):
        # 調用父類中的dispatch
        print('before')
        result = super(Home,self).dispatch(request, *args, **kwargs)
        print('after')
        return result
        
    def get(self,request):
        print(request.method)
        return render(request, 'home.html')
        
    def post(self,request):
        print(request.method,'POST')
        return render(request, 'home.html')


爲了調用自定義的類裏面的方法,在url裏面,咱們須要調用View類的as_view()方法做爲入口。post

好比說學習

# urls.py
from django.conf.urls import url
from myapp.views 
import MyView
urlpatterns = [
    
    url(r'^about/', MyView.as_view()),
]
相關文章
相關標籤/搜索