APIView中的dispatch

(1)dispatch方法詳解----封裝原有的request對象api

(原request中的方法和屬性都可直接在封裝後的request中調用,或者使用request._request也可,如:request.user == request._request.userapp

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
dispatch方法重寫

(2)initialize_request對原生request進行封裝  ide

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
    )
initialize_request封裝request

(3)self.initial詳解----認證+權限+節流+版本控制  spa

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)#頻率組件
self.initial詳解
相關文章
相關標籤/搜索