溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-07-16 13:59:51 來源:億速云 閱讀:112 作者:小新 欄目:開發(fā)技術(shù)

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

一、FBV

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

二、CBV

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

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

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

(1)寫一個處理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請求分配配置

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

到這里,這些方法和function-based view差不多了,要接收request,得到一個response返回。如果方法沒有定義,會拋出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的方式來實現(xiàn)視圖方法的。class相對于function,更能利用多態(tài)的特定,因此更容易從宏觀層面上將項目內(nèi)的比較通用的功能抽象出來。關(guān)于多態(tài),不多解釋,有興趣的同學(xué)自己Google??傊梢岳斫鉃橐粋€東西具有多種形態(tài)(的特性)。

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

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

所以,理解cbv的基礎(chǔ)是,理解Mixin。Django中使用Mixin來重用代碼,一個View Class可以繼承多個Mixin,但是只能繼承一個View(包括View的子類),推薦把View寫在最右邊,多個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ì)還是一個FBV

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

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

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

(3)頁面效果

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

點擊提交post請求:

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是一個類方法,因此views.LoginView.as_view()需要添加(),這樣才調(diào)用這個類方法。

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():這次請求的請求方式小寫。

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

判斷請求方式是否在這個請求方式列表中。

handler就是反射得到的實例方法get,如果找不到則通過http_method_not_allowed返回報錯。

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

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

看完了這篇文章,相信你對“Django中CBV與FBV原理的示例分析”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI