Django中CBV與FBV原理的示例分析-創(chuàng)新互聯(lián)

小編給大家分享一下Django中CBV與FBV原理的示例分析,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

成都創(chuàng)新互聯(lián)專業(yè)提供眉山聯(lián)通機(jī)房服務(wù),為用戶提供五星數(shù)據(jù)中心、電信、雙線接入解決方案,用戶可自行在線購買眉山聯(lián)通機(jī)房服務(wù),并享受7*24小時(shí)金牌售后服務(wù)。

一、FBV

FBV(function base views) 就是在視圖里使用函數(shù)處理請(qǐng)求。

二、CBV

CBV(class base views) 就是在視圖里使用類處理請(qǐng)求。

Python是一個(gè)面向?qū)ο蟮木幊陶Z言,如果只用函數(shù)來開發(fā),有很多面向?qū)ο蟮膬?yōu)點(diǎn)就錯(cuò)失了(繼承、封裝、多態(tài))。所以Django在后來加入了Class-Based-View??梢宰屛覀冇妙悓慥iew。這樣做的優(yōu)點(diǎn)主要下面兩種:

提高了代碼的復(fù)用性,可以使用面向?qū)ο蟮募夹g(shù),比如Mixin(多繼承)
可以用不同的函數(shù)針對(duì)不同的HTTP方法處理,而不是通過很多if判斷,提高代碼可讀性
1、class-based views的使用

(1)寫一個(gè)處理GET方法的view

用函數(shù)寫的話如下所示:

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')

(2)用url請(qǐng)求分配配置

Django的url是將一個(gè)請(qǐng)求分配給可調(diào)用的函數(shù)的,而不是一個(gè)class。針對(duì)這個(gè)問題,class-based view提供了一個(gè)as_view()靜態(tài)方法(也就是類方法),調(diào)用這個(gè)方法,會(huì)創(chuàng)建一個(gè)類的實(shí)例,然后通過實(shí)例調(diào)用dispatch()方法,dispatch()方法會(huì)根據(jù)request的method的不同調(diào)用相應(yīng)的方法來處理request(如get() , post()等)。

到這里,這些方法和function-based view差不多了,要接收request,得到一個(gè)response返回。如果方法沒有定義,會(huì)拋出HttpResponseNotAllowed異常。

在url中,寫法如下:

# urls.py
from django.conf.urls import url
from myapp.views import MyView
urlpatterns = [
   url(r'^index/$', MyView.as_view()),
]

類的屬性可以通過兩種方法設(shè)置,第一種是常見的python的方法,可以被子類覆蓋:

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中設(shè)置類的屬性Python

urlpatterns = [
  url(r'^index/$', GreetingView.as_view(name="egon")),
]

2、使用Mixin

要理解django的class-based-view(以下簡稱cbv),首先要明白django引入cbv的目的是什么。在django1.3之前,generic view也就是所謂的通用視圖,使用的是function-based-view(fbv),亦即基于函數(shù)的視圖。有人認(rèn)為fbv比cbv更pythonic,竊以為不然。python的一大重要的特性就是面向?qū)ο蟆?/p>

而cbv更能體現(xiàn)python的面向?qū)ο蟆bv是通過class的方式來實(shí)現(xiàn)視圖方法的。class相對(duì)于function,更能利用多態(tài)的特定,因此更容易從宏觀層面上將項(xiàng)目內(nèi)的比較通用的功能抽象出來。關(guān)于多態(tài),不多解釋,有興趣的同學(xué)自己Google。總之可以理解為一個(gè)東西具有多種形態(tài)(的特性)。

cbv的實(shí)現(xiàn)原理通過看django的源碼就很容易明白,大體就是由url路由到這個(gè)cbv之后,通過cbv內(nèi)部的dispatch方法進(jìn)行分發(fā),將get請(qǐng)求分發(fā)給cbv.get方法處理,將post請(qǐng)求分發(fā)給cbv.post方法處理,其他方法類似。

怎么利用多態(tài)呢?cbv里引入了mixin的概念。Mixin就是寫好了的一些基礎(chǔ)類,然后通過不同的Mixin組合成為最終想要的類。

所以,理解cbv的基礎(chǔ)是,理解Mixin。Django中使用Mixin來重用代碼,一個(gè)View Class可以繼承多個(gè)Mixin,但是只能繼承一個(gè)View(包括View的子類),推薦把View寫在最右邊,多個(gè)Mixin寫在左邊。

三、CBV示例

1、CBV應(yīng)用簡單示例

########### 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

構(gòu)建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的本質(zhì)還是一個(gè)FBV

(2)url中設(shè)置類的屬性Python:

path('login/', views.LoginView.as_view()),

用戶訪問login,views.LoginView.as_view()一定是一個(gè)函數(shù)名,不是函數(shù)調(diào)用。

(3)頁面效果

Django中CBV與FBV原理的示例分析 

點(diǎn)擊提交post請(qǐng)求:

Django中CBV與FBV原理的示例分析

2、from django.views import View的源碼查看

class View:
  """
  get:查 post:提交,添加 put:所有內(nèi)容都更新  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)]

注意:

(1)as_view方法:

as_view是一個(gè)類方法,因此views.LoginView.as_view()需要添加(),這樣才調(diào)用這個(gè)類方法。

as_view執(zhí)行完,返回是view(函數(shù)名)。因此login一旦被用戶訪問,真正被執(zhí)行是view函數(shù)。

(2)view方法:

view函數(shù)的返回值:

return self.dispatch(request, *args, **kwargs)

這里的self是誰取決于view函數(shù)是誰調(diào)用的。view——》as_view——》LoginView(View的子類)。在子類沒有定義dispatch的情況下,調(diào)用父類的。

self.dispatch(request, *args, **kwargs)是執(zhí)行dispatch函數(shù)。由此可見login訪問,真正被執(zhí)行的是dispatch方法。且返回結(jié)果是dispatch的返回結(jié)果,且一路回傳到頁面顯示。用戶看的頁面是什么,完全由self.dispatch決定。

(3)dispatch方法: (分發(fā))

request.method.lower():這次請(qǐng)求的請(qǐng)求方式小寫。

self.http_method_names:['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

判斷請(qǐng)求方式是否在這個(gè)請(qǐng)求方式列表中。

handler就是反射得到的實(shí)例方法get,如果找不到則通過http_method_not_allowed返回報(bào)錯(cuò)。

3、自定義dispatch

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)

四、postman

谷歌的一個(gè)插件,模擬前端發(fā)get post put delete請(qǐng)求,下載,安裝。 https://www.getpostman.com/apps

看完了這篇文章,相信你對(duì)“Django中CBV與FBV原理的示例分析”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計(jì)公司行業(yè)資訊頻道,感謝各位的閱讀!

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。

文章題目:Django中CBV與FBV原理的示例分析-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://muchs.cn/article26/dpegjg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)網(wǎng)站內(nèi)鏈、手機(jī)網(wǎng)站建設(shè)、商城網(wǎng)站網(wǎng)站導(dǎo)航、網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運(yùn)營