Django rest framework源码阅读(1)----请求流程

实例化CBV,并调用该对象的dispatch方法

  • 当请求到达的时候,首先会被CBV中定义的dispatch处理。
  # Note: Views are made CSRF exempt from within `as_view` as to prevent
    # accidental removal of this exemption in cases where `dispatch` needs to
    # be overridden.
    def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
            self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            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

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response

第一步,将WSGIRequest对象封装成rest_framework.request.Request对象。

    def initialize_request(self, request, *args, **kwargs):
        """
        Returns the initial request object.
        """
        parser_context = self.get_parser_context(request)

        return Request(
            request,
            parsers=self.get_parsers(),   #解析get请求
            authenticators=self.get_authenticators(), #认证相关
            negotiator=self.get_content_negotiator(), # 选择相关
            parser_context=parser_context
        )
  • initialize_request方法中,有一个方法处理过request,view的值是self,代指的是UsersView这个对象,所以get_parser_context方法把UsersView这个类封装进来然后返回,所以get_parser_context方法最后返回的当前对象以及当前对象所传的参数。
    def get_parser_context(self, http_request):
        """
        Returns a dict that is passed through to Parser.parse(),
        as the `parser_context` keyword argument.
        """
        # Note: Additionally `request` and `encoding` will also be added
        #       to the context by the Request object.
        return {
            'view': self,
            'args': getattr(self, 'args', ()),
            'kwargs': getattr(self, 'kwargs', {})
        }
  • 在get_authenticators方法中,获取封装了验证规则的authenticator对象,本质上经过以下流程
    def get_authenticators(self):
        """
        Instantiates and returns the list of authenticators that this view can use.
        """
        
        return [auth() for auth in self.authentication_classes]
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
    api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)    
DEFAULTS = {
	...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    ),
}

第二步,再来看initial这个方法

  • 先执行get_format_suffix来获取客户端所发送的url的后缀,然后执行perform_content_negotiation方法,从它的注释可以知道这个方法的主要作用是执行内容选择,并把接收到的信息保存在request中
  • 这个函数内部完成了四件事
    1. 处理请求中包含的版本信息
    2. 认证授权
    3. 权限验证
    4. 限制用户访问频率
    def initial(self, request, *args, **kwargs):
        """
        Runs anything that needs to occur prior to calling the method handler.
        """
        self.format_kwarg = self.get_format_suffix(**kwargs)

        # Perform content negotiation and store the accepted info on the request
        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg
        # Determine the API version, if versioning is in use.
        # 如果url中有版本信息,就获取发送到服务端的版本,返回一个元组
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme

        # Ensure that the incoming request is permitted
        # 执行认证功能,确认进行后续操作的用户是被允许的.perform_authentication方法返回经过认证的用户对象
        self.perform_authentication(request)
        # 如果用户通过认证,检查用户是否有权限访问url中所传的路径.如用用户访问的是没有没有权限的路径,则会抛出异常.
        self.check_permissions(request)
        # check_throttles方法的作用是检查用户是否被限制了访问主机的次数,如果用户访问服务器的次数超出设定值,则会抛出一个异常
        self.check_throttles(request)

第三步,initial这个方法执行完成后

        try:
            self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            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

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response
  • 在执行initial方法之前,使用了try/except方法来进行异常处理如果执行initial方法的时候出现错误,就调用handle_exception来处理initial方法抛出的异常,返回正确的响应信息,如果initial方法执行完成没有抛出异常,request.method.lower把请求的方法转换成小写,再通过反射的方式来执行UsersView类中的get或post等自定义方法,然后返回响应信息。

第四步,执行finalize_response方法把最终的响应信息返回给客户端的浏览器

    def finalize_response(self, request, response, *args, **kwargs):
        """
        Returns the final response object.
        """
        # Make the error obvious if a proper response is not returned
        assert isinstance(response, HttpResponseBase), (
            'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
            'to be returned from the view, but received a `%s`'
            % type(response)
        )

        if isinstance(response, Response):
            if not getattr(request, 'accepted_renderer', None):
                neg = self.perform_content_negotiation(request, force=True)
                request.accepted_renderer, request.accepted_media_type = neg

            response.accepted_renderer = request.accepted_renderer
            response.accepted_media_type = request.accepted_media_type
            response.renderer_context = self.get_renderer_context()

        # Add new vary headers to the response instead of overwriting.
        vary_headers = self.headers.pop('Vary', None)
        if vary_headers is not None:
            patch_vary_headers(response, cc_delim_re.split(vary_headers))

        for key, value in self.headers.items():
            response[key] = value

        return response

总结请求流程

1.请求到达服务端,经过WSGI和中间件到达路由系统
2.路由系统执行配置的CBV或者FBV中的dispatch方法
3.在dispatch方法中,request方法被封装添加了解析器,认证方法及选择器等方法
4.然后执行initial方法
5.再获取版本,进行认证操作,权限操作和节流操作
6.最后执行自定义的get,post,push,delete等自定义方法
7.在执行initial方法之前,通过try来捕获可能出现的异常
8.如果出现异常,就执行handle_exception方法来处理捕获到的异常
9.不管是否出现异常,最后的返回值都通过finalize_response方法来处理响应的内容

参考链接

源码剖析Django REST framework的请求生命周期

你可能感兴趣的:(Django源码阅读)