APIView中的dispatch
(1)dispatch方法详解----封装原有的request对象
(原request中的方法和属性均可直接在封装后的request中调用,或者使用request._request也可,如:request.user == request._request.user
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 #1.对原来的request进行进一步封装 request = self.initialize_request(request, *args, **kwargs) self.request = request#(2)request已经是经过进一步封装的 self.headers = self.default_response_headers # deprecate? try: #2.增加对request的调用 self.initial(request, *args, **kwargs)#(3)比View中多的执行的方法,使用封装过后的request进行调用 # 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)#(4)对原响应对象进行进一步封装 return self.response
(2)initialize_request对原生request进行封装
def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """ parser_context = self.get_parser_context(request) return Request( request,#(1-1)原来的request parsers=self.get_parsers(),#(1-2)[反序列化方式列表] authenticators=self.get_authenticators(),#(1-3)实例化调用了rest_framework配置文件[中间件的认证类列表]---[BasicAuthentication对象,SessionAuthentication对象] negotiator=self.get_content_negotiator(), parser_context=parser_context )
(3)self.initial详解----认证+权限+节流+版本控制
self.initial(request, *args, **kwargs)#(3)比View中多的执行的方法,使用封装过后的request进行调用 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.(3-0)api版本的获取 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)#(3-1)进行认证是否登录 self.check_permissions(request)#(3-2)权限组件 self.check_throttles(request)#频率组件