一、FBV

  FBV(function base views) 就是在视图里使用函数处理请求。

二、CBV

  CBV(class base views) 就是在视图里使用类处理请求。

  Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。这样做的优点主要下面两种:

  1. 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  2. 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性

1、class-based views的使用

(1)写一个处理GET方法的view

  用函数写的话如下所示:

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是将一个请求分配给可调用的函数的,而不是一个class。针对这个问题,class-based view提供了一个as_view()静态方法(也就是类方法),调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()方法,dispatch()方法会根据request的method的不同调用相应的方法来处理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()),
]

  类的属性可以通过两种方法设置,第一种是常见的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中设置类的属性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),亦即基于函数的视图。有人认为fbv比cbv更pythonic,窃以为不然。python的一大重要的特性就是面向对象。

  而cbv更能体现python的面向对象。cbv是通过class的方式来实现视图方法的。class相对于function,更能利用多态的特定,因此更容易从宏观层面上将项目内的比较通用的功能抽象出来。关于多态,不多解释,有兴趣的同学自己Google。总之可以理解为一个东西具有多种形态(的特性)。cbv的实现原理通过看django的源码就很容易明白,大体就是由url路由到这个cbv之后,通过cbv内部的dispatch方法进行分发,将get请求分发给cbv.get方法处理,将post请求分发给cbv.post方法处理,其他方法类似。怎么利用多态呢?cbv里引入了mixin的概念。Mixin就是写好了的一些基础类,然后通过不同的Mixin组合成为最终想要的类。

  所以,理解cbv的基础是,理解Mixin。Django中使用Mixin来重用代码,一个View Class可以继承多个Mixin,但是只能继承一个View(包括View的子类),推荐把View写在最右边,多个Mixin写在左边。

  更多参考:https://www.cnblogs.com/yuanchenqi/articles/8715364.html

三、CBV示例

1、CBV应用简单示例

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

  构建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的本质还是一个FBV

(2)url中设置类的属性Python:

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

  用户访问login,views.LoginView.as_view()一定是一个函数名,不是函数调用。

(3)页面效果

  

  点击提交post请求:

  

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

class View:
"""
get:查 post:提交,添加 put:所有内容都更新 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'] = ''
return response def _allowed_methods(self):
return [m.upper() for m in self.http_method_names if hasattr(self, m)]

base.py中View类源码

  注意:

(1)as_view方法:

  as_view是一个类方法,因此views.LoginView.as_view()需要添加(),这样才调用这个类方法。

  as_view执行完,返回是view(函数名)。因此login一旦被用户访问,真正被执行是view函数。

(2)view方法:

  view函数的返回值:

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

  这里的self是谁取决于view函数是谁调用的。view——》as_view——》LoginView(View的子类)。在子类没有定义dispatch的情况下,调用父类的。

  self.dispatch(request, *args, **kwargs)是执行dispatch函数。由此可见login访问,真正被执行的是dispatch方法。且返回结果是dispatch的返回结果,且一路回传到页面显示。用户看的页面是什么,完全由self.dispatch决定。

(3)dispatch方法:  (分发)

  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

  谷歌的一个插件,模拟前端发get post put delete请求,下载,安装。https://www.getpostman.com/apps

Django——CBV与FBV的更多相关文章

  1. Django CBV和FBV

    Django CBV和FBV Django内部CBV内部接收方法操作: 1.通过客户端返回的请求头RequestMethod与RequesrtURL,会以字符串形式发送到服务器端. 2.取到值后通过d ...

  2. django CBV和FBV写法总结

    一.FBV function base views 平常我们的写法,一个URL对应一个视图函数 二.CBV 1.url 配置 path('test/',views.CBVTest.as_views() ...

  3. Django - CBV、FBV

    一.FBV FBV(function base views) 就是在视图里使用函数处理请求. 在之前django的学习中,我们一直使用的是这种方式. 二.CBV CBV(class base view ...

  4. Django CBV与FBV

    FBV FBV(function base views) 就是在视图里使用函数处理请求. CBV CBV(class base views) 就是在视图里使用类处理请求. Python是一个面向对象的 ...

  5. Python/Django(CBV/FBV/ORM操作)

    Python/Django(CBV/FBV/ORM操作) CBV:url对应的类(模式) ##====================================CBV操作============ ...

  6. Django(视图 CBV、FBV)

    day67 参考:http://www.cnblogs.com/liwenzhou/articles/8305104.html CBV和FBV 我们之前写过的都是基于函数的view,就叫FBV.还可以 ...

  7. django中的FBV和CBV

    django中请求处理方式有2种:FBV 和 CBV 一.FBV FBV(function base views) 就是在视图里使用函数处理请求. 看代码: urls.py from django.c ...

  8. Django中的CBV和FBV

    Django中的CBV和FBV 一.  CBV CBV是采用面向对象的方法写视图文件. CBV的执行流程: 浏览器向服务器端发送请求,服务器端的urls.py根据请求匹配url,找到要执行的视图类,执 ...

  9. django视图 CBV 和 FBV

    目录 视图 CBV 和 FBV 什么是视图? FBV function based view 基于函数的视图 CBV class based view 基于类的视图 小技巧 CBV 如何获取页面请求类 ...

随机推荐

  1. UX | 最小可行性技能

    简评:本文介绍了最小 UX 需要技能(可以看成设计版 MVP),包括用不同视角看事情,从回馈中学习等等 ~ 呐,可能刚入门设计的时候,会让一堆工具弄得眼花缭乱.其实呢,并不一定要每样都会使用,举一反三 ...

  2. IPython&Jupyter私房手册

    Jupyter是以Ipython为基础,可以极大的方便开发,对于如何使用,网上的资料都不太全.因此决定自己编写一个私房手册方便随时查找. 1. 安装和配置 安装不多说,不想折腾直接安装anaconda ...

  3. js 删除removeChild与替换replaceChild

    <input type="button" value="删除" id="btn" /> <input type=" ...

  4. Java实现二维码生成的方法

    1.支持QRcode.ZXing 二维码生成.解析: package com.thinkgem.jeesite.test; import com.google.zxing.BarcodeFormat; ...

  5. json、xml

    json:(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式.简单地说,JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然 ...

  6. Fliptile (dfs+二进制压缩)

    Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He ha ...

  7. 上海高校程序设计竞赛 D CSL 的字符串 ( 贪心)

    题目描述 CSL 以前不会字符串算法,经过一年的训练,他还是不会……于是他打算向你求助. 给定一个字符串,只含有可打印字符,通过删除若干字符得到新字符串,新字符串必须满足两个条件: 原字符串中出现的字 ...

  8. C++ GUI Qt4 编程 (第二版)

    [加拿大]JasminBlanchette [英]MarkSummerfield . 电子工业 2008. 前几天的问题多是因为版本不兼容的问题. QT本身Q4 Q5就有版本问题,然后集成到VS08 ...

  9. [转] node.js如何获取时间戳与时间差

    [From] http://www.jb51.net/article/89767.htm Nodejs中获取时间戳的方法有很多种,例如: 1.new Date().getTime()  2.Date. ...

  10. Java 安全套接字编程以及 keytool 使用最佳实践

    Java 安全套接字编程以及 keytool 使用最佳实践 http://www.ibm.com/developerworks/cn/java/j-lo-socketkeytool/