美文网首页
Django源码分析--01类视图

Django源码分析--01类视图

作者: 梦醒家先生 | 来源:发表于2018-07-05 23:55 被阅读0次

    1.类视图的引入

    以函数的方式定义的视图称为函数视图,函数视图便于理解。但是遇到一个视图对应的路径提供了多种不同HTTP请求方式的支持时,便需要在一个函数中编写不同的业务逻辑,代码可读性与复用性都不佳。

    def register(request):
        """处理注册"""
    
        # 获取请求方法,判断是GET/POST请求
        if request.method == 'GET':
            # 处理GET请求,返回注册页面
            return render(request, 'register.html')
        else:
            # 处理POST请求,实现注册逻辑
            return HttpResponse('这里实现注册逻辑')
    

    Django中也可以使用类来定义一个视图,称为类视图。

    使用类视图可以将视图对应的不同请求方式以类中的不同方法来区别定义。如下所示

    from django.views.generic import View
    
    class RegisterView(View):
        """类视图:处理注册"""
          '''
          1. 继承View类中的as_view方法:
          2. cls:代表当前的继承类RegisterView
          def as_view(cls, **initkwargs):
               ....
               
              return view
          '''
        def get(self, request):
            """处理GET请求,返回注册页面"""
            return render(request, 'register.html')
    
        def post(self, request):
            """处理POST请求,实现注册逻辑"""
            return HttpResponse('这里实现注册逻辑')
    

    类视图的好处:

    • 代码可读性好
    • 类视图相对于函数视图有更高的复用性, 如果其他地方需要用到某个类视图的某个特定逻辑,直接继承该类视图即可

    2 类视图使用

    定义类视图需要继承自Django提供的父类View,可使用
    from django.views.generic import View或者
    from django.views.generic.base import View 导入,定义方式如上所示。

    • 配置路由时,使用类视图的as_view()方法来添加。
    urlpatterns = [
        # 视图函数:注册
        # url(r'^register/$', views.register, name='register'),
        # 类视图:注册
        url(r'^register/$', views.RegisterView.as_view(), name='register'),
    ]
    

    3 类视图原理

    • 3.1首先了解getattr方法的作用:
    class A(object):
    
        def get(self, request):
    
            print(request)
    
    a = A()
    # 传入a对象,来查询-->类A的对象中有没有'get'这个方法或者属性-->查询到以后返回给func
    func = getattr(a, 'get')
    
    # 查询到A类中有get方法,就执行类方法get
    func(66666)
    
    # 执行结果
    66666
    
    • 3.2 继承的父类View是
    class View(object):
        """
        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 six.iteritems(kwargs):
                setattr(self, key, value)
    

    类属性:http_method_names :储存了所有请求方法

    • 3.3 as_view是View类中类方法
      请求-响应过程的主要入口点。
    @classonlymethod
        def as_view(cls, **initkwargs):
            '''
            # cls 代表当前类,类视图继承View以后,调用as_view,就代表类继承类
            '''
            """
            Main entry point for a request-response process.
            请求-响应过程的主要入口点。
            """
            for key in initkwargs:
                '''
                # 判断继承类中request请求对象获取的请求方式
                '''
                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
              '''
                # view接收类方法dispatch引用
              '''
                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给as_view的方法view引用,方法view接收dispatch类方法引用
            '''
            return view
    
    • 参数cls:就是代表当前类,继承View类以后类视图,cls代表了继承类
    • as_view方法是两层函数的嵌套,返回 return view
    • view是as_view的嵌套的函数
    • view返回了 return self.dispatch(request, *args, **kwargs)
    • dispatch又是 类View的方法
    • 3.4 类View中dispatch方法
      主要逻辑就是类方法dispatch来判断request对象获取请求方式
    '''
    # 对不同的请求方式,返回不同的请求结果
    '''
    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)
    
    • dispatch方法接收request对象请求参数
    • 判断请求方式是否在类属性http_method_names列表中
    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.method获取请求方式,将请求参数lower()转换小写,是否在类属性:http_method_names

    • dispatch方法中使用getattr方法
      self:代表当前的类View的实例对象
      类View:被类视图继承,就继承了as_view类方法(
      getattr:方法就开始查询继承的类中,有没有request.method.lower()请求的方法
    • 查询到有需要的请求方法就返回给handler
      return handler(request, *args, **kwargs)
    • handler返回给view
    • view返回给as_view

    相关文章

      网友评论

          本文标题:Django源码分析--01类视图

          本文链接:https://www.haomeiwen.com/subject/lrumuftx.html