• CBV源码分析


    FBV和CBV

    FBV(function base views) : 在视图层中使用函数处理请求

    CBV(class base views): 在视图层中使用类处理请求

    Python是一个面向对象的编程语言, 面向对象的优点(继承,封装,多态), 使用CBV,用类写view,这样的做的优点:

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

    CBV简单示例

    # 在urls.py中进行路由配置
    urlpatterns = [
        # (正则表达式,  函数内存地址)
        url(r'^admin/', admin.site.urls),
        url(r'^books/$', views.Books.as_view()),
    ]
    
    # views视图中
    from django.views import  View
    class Books(View):
        def get(self,request, *args, **kwargs):
            print("get")
            return HttpResponse("ok")
    
        def dispatch(self, request, *args, **kwargs):
            print("dispatch")
            ret = super(Books,self).dispatch(request, *args, **kwargs)
            print("ret",ret)
            return  HttpResponse(ret)
          
    '''
    输出结果为:
    dispatch
    get
    ret <HttpResponse status_code=200, "text/html; charset=utf-8">
    '''
    
    

    源码分析

    # 从views.Books.as_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
    

    由于配置的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_nameshttp_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

    as_view函数下内置一个方法def view(request, *args, **kwargs):

    				
      # 函数可以当做对象来使用, 一切皆对象
      # 为view函数添加了属性
      			view.view_class = cls
            view.view_initkwargs = initkwargs
    
          
      # 再次对view函数添加属性
            # 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=())
    
    # 点进 update_wrapper
    
    WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__',
                           '__annotations__')
    WRAPPER_UPDATES = ('__dict__',)
    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函数添加了一些属性,用来更新某些操作,以及可以获取某些数据操作,比如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)
            view.view_class = cls
            view.view_initkwargs = initkwargs
    
    
    

    为本类实例对象赋值request、args、kwargs,最后执行return self.dispatch(request, *args, **kwargs) (相当于一个装饰器的功能, 可以自定义内容) , 所以views.Books.as_view()中的url配置最后会返回view方法

    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列表中,没有的话进行相关处理,赋值操作handlerhandler = self.http_method_not_allowed

    如果没有找到, 就会构造一个默认的

        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(request, *args, **kwargs),其实就是执行代码中CBVBooksget方法

  • 相关阅读:
    redis/memcached可视化客户端工具TreeNMS
    Navicat Mysql快捷键
    mysql全文索引之模糊查询
    Discuz网警过滤关键词库
    php中的implements 使用详解
    PHP 依赖注入和控制反转再谈(二)
    php 中的closure用法
    C# 反射(Reflection)技术
    Oracle pl/sql编程值控制结构
    Oracle PL/SQL编程之变量
  • 原文地址:https://www.cnblogs.com/kp1995/p/10596248.html
Copyright © 2020-2023  润新知