欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django CBV與FBV原理及實(shí)例詳解

 更新時(shí)間:2019年08月12日 09:54:32   作者:休耕  
這篇文章主要介紹了Django CBV與FBV原理及實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

一、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)頁面效果

 

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

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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python讀寫操作csv和excle文件代碼實(shí)例

    Python讀寫操作csv和excle文件代碼實(shí)例

    這篇文章主要介紹了python讀寫操作csv和excle文件代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • python函數(shù)遞歸調(diào)用的實(shí)現(xiàn)

    python函數(shù)遞歸調(diào)用的實(shí)現(xiàn)

    本文主要介紹了python函數(shù)遞歸調(diào)用的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05
  • Python學(xué)習(xí)之日志模塊詳解

    Python學(xué)習(xí)之日志模塊詳解

    說到日志,我們完全可以想象為現(xiàn)實(shí)生活中的日記。日記是我們平時(shí)記錄我們生活中點(diǎn)點(diǎn)滴滴的一種方法,而日志我們可以認(rèn)為是 程序的日記 ,程序的日記是用來記錄程序的行為。本文將詳細(xì)介紹Python中的日志模塊(logging),需要的可以參考一下
    2022-03-03
  • python添加列表元素append(),extend()及?insert()

    python添加列表元素append(),extend()及?insert()

    這篇文章主要介紹了python添加列表元素append(),extend()及?insert(),列表是儲(chǔ)存元素的數(shù)據(jù)類型,既然能存儲(chǔ)元素,那么就類似數(shù)據(jù)庫一樣,增刪改查的一些功能就不能少了。下面我們就來先看看添加列表元素方法有哪些,需要的朋友可以參考一下
    2022-03-03
  • Python help()函數(shù)用法詳解

    Python help()函數(shù)用法詳解

    這篇文章主要介紹了Python help()函數(shù)的作用,并舉例說明它的詳細(xì)用法,需要的朋友可以參考下
    2014-03-03
  • Python3 實(shí)現(xiàn)遞歸求階乘

    Python3 實(shí)現(xiàn)遞歸求階乘

    這篇文章主要介紹了Python3 實(shí)現(xiàn)遞歸求階乘的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • 關(guān)于numpy.concatenate()函數(shù)的使用及說明

    關(guān)于numpy.concatenate()函數(shù)的使用及說明

    這篇文章主要介紹了關(guān)于numpy.concatenate()函數(shù)的使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • python opencv旋轉(zhuǎn)圖像(保持圖像不被裁減)

    python opencv旋轉(zhuǎn)圖像(保持圖像不被裁減)

    這篇文章主要為大家詳細(xì)介紹了python opencv旋轉(zhuǎn)圖像,保持圖像不被裁減,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • python爬蟲正則表達(dá)式之處理換行符

    python爬蟲正則表達(dá)式之處理換行符

    本文是腳本之家小編剛學(xué)習(xí)python記錄的關(guān)于python爬蟲正則表達(dá)式之處理換行符的相關(guān)資料,需要的朋友可以參考下
    2018-06-06
  • Python中Pexpect庫的使用

    Python中Pexpect庫的使用

    本文主要介紹了Python中Pexpect庫的使用,我們討論了 pexpect 的三種方法,它們可用于執(zhí)行不同的功能,并且它們可以一起使用以使其成為一個(gè)大函數(shù),感興趣的可以了解下
    2023-10-10

最新評(píng)論