2.1 CBV源码分析
FBV : function base views ,就是在视图里使用函数处理请求,这个是最基本的django视图方法,在这里就不再赘述。
CBV : class base views,就是在视图里使用类处理请求。
使用CBV,优点主要有两种: 1、提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承) 2、可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性。
这里我们直接使用上面的代码来看下如何使用CBV模式:
1、 首先从quickstart/urls.py入手
urlpatterns = [ url(r'^index/$',views.IndexView.as_view()), ]
2、quickstart/views.py
from django.views import View class IndexView(View): def get(self,request, *args, **kwargs): print("get") return HttpResponse("ok") def dispatch(self, request, *args, **kwargs): print("dispatch") ret = super(IndexView,self).dispatch(request, *args, **kwargs) print("ret",ret) return HttpResponse(ret)
运行,输入:http://127.0.0.1:8018/index ,可以看到输出结果如下:
dispatch get ret <HttpResponse status_code=200, "text/html; charset=utf-8"> [07/Oct/2018 15:52:08] "GET /index/ HTTP/1.1" 200 2
我们分析源码从路由配置开始,url(r'^index/$',views.IndexView.as_view()),我们进入as_view(),这里我们直接贴出class View的源码:
class View: """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """ 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): ... def http_method_not_allowed(self, request, *args, **kwargs): ... def options(self, request, *args, **kwargs): ... def _allowed_methods(self): ...
由于我们的配置中views.IndexView.as_view()参数为null,所以在for key in initkwargs会直接跳过,如果不为null,就去判断执行接下来的代码,大概意思就是,if key in cls.http_method_names:和if not hasattr(cls, key):,如果传递过来的字典中某键包含在 http_method_names 列表中和本类中没有该键属性都会跑出异常,http_method_names列表如下
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
接着执行一下代码片段:
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.view_class = cls和view.view_initkwargs = initkwargs就是为那个view函数添加了属性,函数也可以当做对象来使用,这在django框架中非常常见,最后通过update_wrapper(view, cls, updated=())和update_wrapper(view, cls.dispatch, assigned=())进行了再次对view函数的属性添加 比如:
urlpatterns = [ url(r'^index/$',views.IndexView.as_view(name="safly")) ] def update_wrapper(wrapper, wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES): """Update a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) updated is a tuple naming the attributes of the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES) """ for attr in assigned: try: value = getattr(wrapped, attr) except AttributeError: pass else: setattr(wrapper, attr, value) for attr in updated: getattr(wrapper, attr).update(getattr(wrapped, attr, {})) # Issue #17482: set __wrapped__ last so we don't inadvertently copy it # from the wrapped function when updating __dict__ wrapper.__wrapped__ = wrapped # Return the wrapper so this can be used as a decorator via partial() return wrapper
个人认为就是为view函数,添加了一些属性,用来更新某些操作,以及可以获取某些数据操作。
最后return view,就是调用as_view函数下的内置函数view():
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)
通过源码可以看出,为本类实例对象赋值:request、args、kwargs,最后执行return self.dispatch(request, args, *kwargs)
所以说,views.IndexView.as_view()中的url配置最后会返回view()方法。对本类对象进行了一些封装: self.request = request self.args = args self.kwargs = kwargs 最后再调用dispatch函数:
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)
上述代码通过判断request的请求方式,通过反射的方式,判断是否在http_method_names列表中,没有的话进行相关处理,赋值操作handler,handler = self.http_method_not_allowed 我们索性来看下handler的输出,它是一个函数
handler <bound method IndexView.get of <app01.views.IndexView object at 0x0661BE10>> # 如果没有找到,就会构造一个默认的,代码如下: 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 http.HttpResponseNotAllowed(self._allowed_methods()) class HttpResponseNotAllowed(HttpResponse): status_code = 405 def __init__(self, permitted_methods, *args, **kwargs): super(HttpResponseNotAllowed, self).__init__(*args, **kwargs) self['Allow'] = ', '.join(permitted_methods) def __repr__(self): return '<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>' % { 'cls': self.__class__.__name__, 'status_code': self.status_code, 'content_type': self._content_type_for_repr, 'methods': self['Allow'], }
所以handler是一个绑定了IndexView中get函数的一个函数,代码的最后handler(request, args, *kwargs)方法执行,其实就是执行我们代码中CBV类IndexView的get方法:
def get(self,request, *args, **kwargs): return HttpResponse("ok")
最后返回return http.HttpResponseNotAllowed(self._allowed_methods())
<HttpResponse status_code=200, "text/html; charset=utf-8">
它是一个对象是继承自HttpResponse的对象,也就是在我们的代码中返回即可。
所以最终的结果是:
dispatch get ret <HttpResponse status_code=200, "text/html; charset=utf-8"> [07/Oct/2018 15:52:08] "GET /index/ HTTP/1.1" 200 2
整个流程: