叽叽喳喳,嘻嘻哈哈

导航

django rest framework 一个请求的大致处理流程

    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)  # 创建 Request 对象
        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)  # 进入 GET, POST, PATCH, PATCH 等 View 下面的各个方法的处理逻辑 

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

        self.response = self.finalize_response(request, response, *args, **kwargs)  # 对 response 对象进行进一步处理
        return self.response  # 返回给客户端
     
    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.
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme

        # Ensure that the incoming request is permitted
        self.perform_authentication(request)  # 认证
        self.check_permissions(request)  # 权限检查
        self.check_throttles(request)  # 限流

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset()) # 分步执行,等于下面两句
        # all_queryset = self.get_queryset()  # 获取所有的结果
        # queryset = self.filter_queryset(all_queryset)  # 过滤结果(可以是根据多种因素进行过滤,例如权限)

        page = self.paginate_queryset(queryset)  # 分页
        if page is not None:
            serializer = self.get_serializer(page, many=True)  # 对分页结果进行反序列化
            return self.get_paginated_response(serializer.data)  # 返回分页结果

        serializer = self.get_serializer(queryset, many=True)  # 反序列化
        return Response(serializer.data)  # 返回结果

posted on 2020-08-01 16:21  叽叽喳喳,嘻嘻哈哈  阅读(157)  评论(0编辑  收藏  举报