FBV和CBV

FBV(function base views) 就是在视图里使用函数处理请求。 
在之前django的学习中,我们一直使用的是这种方式,所以不再赘述。

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

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

CBV简单示例

我们简单来看下如何使用CBV模式,然后在分析下源代码是如何执行的 
urls.py中进行路由配置,源码之后在讲解

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

 

views视图中

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://localhost:8000/index/ 
以此输出

dispatch
get
ret <HttpResponse status_code=200, "text/html; charset=utf-8">

源码分析

我们分析源码从路由配置开始,url(r'^index/$',views.IndexView.as_view()),这里的url配置,我就省去url的方法分析了,可以参考我之前的博客
直接就从views.IndexView.as_view()入手,我先贴出来View类的代码,这里只包含as_view方法,其他的方法先省略,用到的时候在单独贴出来


class View(object):
    http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

    def __init__(self, **kwargs):
        "省略"

    @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):
       "省略"

 

as_view方法代码不多,简单分析如下: 
由于我们的配置中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']

 

继续跟进代码是as_view方法内置的一个函数,该函数如下,函数体先省略

def view(request, *args, **kwargs):

 

暂时跳过as_view函数,执行如下代码片段

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=())

 

什么意思呢?我们可以在url中指定类的属性,比如如下的配置(我这个例子没有指定)

urlpatterns = [
url(r'^index/$',views.IndexView.as_view(name="safly"))
]

 

view.view_class = cls和view.view_initkwargs = initkwargs就是为那个view函数添加了属性,函数也可以当做对象来使用,这在django框架中非常常见,最后通过update_wrapper(view, cls, updated=())和update_wrapper(view, cls.dispatch, assigned=())进行了再次对view函数的属性添加

WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
                       '__annotations__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = 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函数添加了一些属性,用来更新某些操作,以及可以获取某些数据操作,比如WRAPPER_UPDATES = ('__dict__',)从字面意思就可以看出,后续我们在看看能不能发现其他的作用

最后我们终于可以来看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配置最后会return self.dispatch(request, *args, **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列表中,没有的话进行相关处理,赋值操作handlerhandler = 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是一个绑定了IndexViewget函数的一个函数,

代码的最后handler(request, *args, **kwargs)方法执行,其实就是去依次执行http_method_not_allowed函数,继续去执行我们代码中CBVIndexViewget方法

    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的对象 
也就是在我们的代码中返回即可

 def dispatch(self, request, *args, **kwargs):
        ret = super(IndexView,self).dispatch(request, *args, **kwargs)
        return  HttpResponse(ret)

 

以上就是CBV的执行流程,接下来继续分析基于django中的restful framework框架下的APIView

posted on 2018-04-08 21:32  Py行僧  阅读(194)  评论(0编辑  收藏  举报