Django中CBV源码解析

使用

关于FBV和CBV的使用在之前有提到,点击穿越

准备

首先在视图中创建一个类并继承 django.views.View 类,在类中可定义各种请求方式对应执行的函数(函数名为请求方式名称小写)。

1 from django.views import View
2 
3 
4 class TestView(View):
5     def get(self, request):
6         return HttpResponse('get')
7 
8     def post(self, request):
9         return HttpResponse('post')

配置路由。

1 from django.conf.urls import url
2 from app import views
3 urlpatterns = [
4     url(r'^test/', views.TestView.as_view()),
5 ]

源码

做好上述准备之后,就可以通过相应的请求方法请求对应路由地址来执行CBV视图中对应请求方法名的函数,为什么Django能帮我们做到这一点呢?我们知道,在使用FBV时,路由地址对应的是一个函数句柄,而在CBV中,路由地址对应的是视图类的 as_view 函数的执行结果。例如:

 1 from django.conf.urls import url
 2 from app import views
 3 
 4 def test():
 5     pass
 6 
 7 urlpatterns = [
 8     url(r'^test_FBV/', test),
 9     url(r'^test_CBV/', views.TestView.as_view()),
10 ]

所以从这里就可以看出, as_view 函数的返回值一定也是一个函数句柄。查看as_view()函数源码:

 1 class View(object):
 2 
 3     @classonlymethod
 4     def as_view(cls, **initkwargs):
 5         for key in initkwargs:
 6             if key in cls.http_method_names:
 7                 raise TypeError("You tried to pass in the %s method name as a "
 8                                 "keyword argument to %s(). Don't do that."
 9                                 % (key, cls.__name__))
10             if not hasattr(cls, key):
11                 raise TypeError("%s() received an invalid keyword %r. as_view "
12                                 "only accepts arguments that are already "
13                                 "attributes of the class." % (cls.__name__, key))
14 
15         def view(request, *args, **kwargs):
16             self = cls(**initkwargs)
17             if hasattr(self, 'get') and not hasattr(self, 'head'):
18                 self.head = self.get
19             self.request = request
20             self.args = args
21             self.kwargs = kwargs
22             return self.dispatch(request, *args, **kwargs)
23         view.view_class = cls
24         view.view_initkwargs = initkwargs
25 
26         update_wrapper(view, cls, updated=())
27 
28         update_wrapper(view, cls.dispatch, assigned=())
29         return view

直接看 29 行, as_view 函数的返回值其实就是 15 行定义的 view 函数。也就是说当请求对应地址时,实际上执行的是这个 view 函数,

从 17 、 18 行可以看出,当我们在视图类中定义了 get 函数而没有定义 head 函数时,就定义一个 head 函数指向了 get 函数。也就是说当只定义了 get 函数而以 head 方式请求时,会执行 get 函数。

再看 22 行, view 函数的返回值其实是 dispatch 函数的执行结果,看源码:

1 class View(object):
2     http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
3     def dispatch(self, request, *args, **kwargs):
4         if request.method.lower() in self.http_method_names:
5             handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
6         else:
7             handler = self.http_method_not_allowed
8         return handler(request, *args, **kwargs)

我们会发现,dispatch方法很简单,就是判断当前请求方法名称是否包含在 http_method_names 这个列表中。如果包含,则通过 getattr 从当前视图类实例中获取该方法名称函数句柄赋值给 handler ,最后执行。也就是说如果请求方式为 put ,就会调用视图类中的 put 函数;如果请求方式为 patch ,就会调用视图类中的 patch 函数。

原文地址:https://www.cnblogs.com/zze46/p/9930665.html