Django之CBV

Django 视图本质是一个函数:接受 HttpRequest 对象作为参数,返回一个 HttpResponse 对象作为返回。FBV 直接就是这样一个函数,而 CBV 类的方法 as_view(),它的返回也是这样一个函数。

CBV(class base views)

就是在视图里使用类处理请求。

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

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

如果我们要写一个处理GET方法的view,用函数写的话是下面这样。

1
2
3
4
5
from django.http import HttpResponse

def my_view(request):
if request.method == 'GET':
return HttpResponse('OK')

如果用class-based view写的话,就是下面这样

1
2
3
4
5
6
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中,就这么写:

1
2
3
4
5
6
7
# urls.py
from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
url(r'^index/$', MyView.as_view()),
]

类的属性可以通过两种方法设置,第一种是常见的Python的方法,可以被子类覆盖。

1
2
3
4
5
6
7
8
9
10
11
12
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

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

CBV流程分析

应用视图

1
2
3
4
5
6
7
8
from django.shortcuts import HttpResponse
from django.views import View

class TestView(View):
def get(self, request):
return HttpResponse('我是get')
def post(self, request):
return HttpResponse('我是post')

URL路由

1
2
3
4
5
6
7
from django.urls import path

from myapp import views

urlpatterns = [
path('', views.TestView.as_view())
]

前端渲染

img

思路

我们想下我们访问下路由,路由怎么知道将请求分配给哪个方法去处理呢?

我们肯定要从源头路由开始找寻答案,路由中我们使用了views.TestView.as_view(),调用了视图方法,我们去视图类中并没有发现as_view()方法,但是该类继承了Django内置类View,我们应该去View中继续找答案

在View类中,我们确实找了类方法as_view(),我们来看下该方法源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36


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.setup(request, *args, **kwargs)
if not hasattr(self, 'request'):
raise AttributeError(
"%s instance has no 'request' attribute. Did you override "
"setup() and forget to call super()?" % cls.__name__
)
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

我们在最后可以看到该方法返回了一个view,在as_view方法中刚好定义了一个view方法,我们需要把矛头指向view方法了。我们在该犯法最后又看到它返回了一个self.dispatch(request, *args, **kwargs),又转手了?

我们继续找dispatch方法,我们在View类下又找到了dispatch方法,源码如下:

1
2
3
4
5
6
7
8
9
10

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)

View最上面定义的类属性:

1
2

http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

结合上下大概意思很明了了,用户发起请求,dispatch根据其请求类型,通过反射获取到该类以请求类型命名的方法。即用户发起get请求,就分发到get方法,依次类推,这就是CBV分发请求的整个流程。

CBV高级用法

Django还帮我们封装了很多通用的视图组件,关于这部分详细介绍见:Django之通用视图组件