Django的FBV和CB
Django的FBV和CBV
FBV
FBV(function base views) 就是在视图里使用函数处理请求。
在之前django的学习中,我们一直使用的是这种方式,所以不再赘述。
CBV
CBV(class base views) 就是在视图里使用类处理请求。
Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。这样做的优点主要下面两种:
- 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
- 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性
使用class-based views
如果我们要写一个处理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')

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()),
]

我们可以看看as_view这个方法的源码

@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

可以看到as_view最终的执行结果就是返回了一个view函数,而在url中其实我们就是在调用这个函数,这个函数先是实例化出了一个View类的对象,最后返回的是这个对象的dispatch方法的执行结果
那么这个dispatche方法又干了什么呢

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)

这个方法其实就是判断我们的请求方法,并根据请求方法执行相应的方法对应的函数
类的属性可以通过两种方法设置,第一种是常见的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")),
]
使用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写在左边。
关于csrf_token的装饰器
我们知道当我们向django发送post请求时,有一个中间件会检验csrf_token,如果我们不想使用它可以将它注释,同样我们也可以通过装饰器来避免发送POST请求时被服务器拒绝

from django.shortcuts import render, HttpResponse
from django.views import View
# Create your views here.
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.utils.decorators import method_decorator @csrf_exempt # 避免csrf验证
def foo(request):
return HttpResponse("foo") # 方式1
# @method_decorator(csrf_exempt, name="dispatch")
class IndexView(View):
# 方式2
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
print("hello world")
# 执行父类的dispatch方法
res = super(IndexView, self).dispatch(request, *args, **kwargs)
return res def get(self, request, *args, **kwargs):
return HttpResponse("index") def post(self, request, *args, **kwargs):
return HttpResponse("post index") def delete(self, request):
return HttpResponse("delete index")

可以看到FBV和CBV的形式都可以通过装饰器的形式来实现,还有一个csrf_protect是可以在中间件被注释时也可以进行验证
Django的FBV和CB的更多相关文章
- Python/Django(CBV/FBV/ORM操作)
Python/Django(CBV/FBV/ORM操作) CBV:url对应的类(模式) ##====================================CBV操作============ ...
- django的FBV和CBV
title: python djano CBV FBV tags: python, djano, CBV, FBV grammar_cjkRuby: true --- python django的fu ...
- Django之FBV与CBV
一.FBV与CBV FBV(function based views),即基于函数的视图:CBV(class based views),即基于类的视图,也是基于对象的视图.当看到这个解释时,我是很萌的 ...
- django的FBV和CBV的装饰器例子
备忘 def auth(func): def inner(request,*args,**kwargs): u = request.COOKIES.get('username111') if not ...
- Django之FBV&CBV
CBV与FBV是django视图中处理请求的两种方式 FBV FBV也就是function base views,字面意思函数基础视图,使用函数的方式处理请求url分发中添加的参数为视图处理函数名, ...
- Django之FBV和CBV的用法
FBV FBV,即 func base views,函数视图,在视图里使用函数处理请求. 以用户注册代码为例, 使用两个函数完成注册 初级注册代码 def register(request): &qu ...
- [oldboy-django][2深入django]FBV + CBV + 装饰器
FBV django CBV & FBV - FBV function basic view a. urls 设置 urls(r'^test.html$', views.test) b. vi ...
- django之分页、cookie装饰器
一.分页代码如下 from django.utils.safestring import mark_safe class Page: def __init__(self, current_page, ...
- Django web 基础
一.Django概述 Django大而全; 创建Django工程:django-admin startproject sitename 创建django之后生成的目录结构如下: Project Pro ...
随机推荐
- C语言中do...while(0)的妙用-避免goto
使用goto的优雅并避免结构的混乱 将要跳转到的语句用do{-}while(0) 包起来就可以. reference #defien N 10 bool Execute() { // 分配资源 int ...
- java中Date的使用情况
在开发中常使用情况. 1.将String转为date 例如"201604131630" //设置日期格式 public SimpleDateFormat sdf = new Si ...
- abs()
abs() 用于返回一个数值的绝对值 In [1]: abs(10) Out[1]: 10 In [2]: abs(-10) Out[2]: 10 In [3]: abs(-10.9) Out[3]: ...
- kubectl get 输出格式
常见的输出格式有: * custom-columns=<spec> # 根据自定义列名进行输出,逗号分隔 * custom-columns-file=<filename> # ...
- RecyclerView的通用适配器,和滚动时不加载图片的封装
对于RecyclerView我们需要使用RecyclerAdapter,使用方式与ListViewAdapter类似,具体代码大家可以在网上搜索,这里就只教大家使用封装后的简洁RecyclerAdap ...
- LLDB调试器
你是否曾经苦恼于理解你的代码,而去尝试打印一个变量的值? NSLog(@"%@", whatIsInsideThisThing); 或者跳过一个函数调用来简化程序的行为? NSNu ...
- django restframwork教程之Request和Response
从这一篇文章开始,我们会覆盖整个REST framwork框架的核心,接下来让我们介绍一些基础的构建块 Request 对象 REST framework 引入了一个扩展HttpRequest的请求对 ...
- js+jquery(二)
1.获取列表框所选中的全部选项的值 $("select").change(function() { // 设置列表框change 事件 // 获取列表框所选中的全部选项的值 ale ...
- Eclipse 真机调试检测不到手机解决方案
想用Eclipse真机调试,但是死活检测不到手机. 手机已经打开了usb调试模式. 开始用的华为Mate9,后面试了下小米,都不行. 在网上搜了一堆,什么安全驱动.adb占用.删除360手机助手.修改 ...
- 【BZOJ2453】维护队列/【BZOJ2120】数颜色 分块
[BZOJ2453]维护队列 Description 你小时候玩过弹珠吗? 小朋友A有一些弹珠,A喜欢把它们排成队列,从左到右编号为1到N.为了整个队列鲜艳美观,小朋友想知道某一段连续弹珠中,不同颜色 ...