等到上面的过程执行完成后,再执行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所以总结:
REST framework请求的生命周期为:
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方法来处理响应的内容