drf certification authority throttling the flow source

Call dispatch method, IndexView view looking from the beginning, looking APIview itself does not exist, APIview stop in existence, namely the call dispatch method APIview

APIview of dispatch

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

View of dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    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
    return handler(request, *args, **kwargs)

Two of operation is important

request = self.initialize_request(request, *args, **kwargs)
self.initial(request, *args, **kwargs)

initialize_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(),
        authenticators=self.get_authenticators(),
        negotiator=self.get_content_negotiator(),
        parser_context=parser_context
    )

In fact, here it is the return of a Request object, which encapsulates the original request, as well as important point is authenticators

request primitive is assigned to the objects Request._request authenticate attribute is obtained from get_authenticators () to this method

And this return to the Request object assigned to the call to dispatch a view self.request.

initial

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) # 频率验证

Authenticate authentication
normal execution as_view (), returns after dispatch, dispatch access URL execution method, a method to perform a method corresponding to the reflection of the view class.

perform_authentication
certification is actually the initial perform_authentication:

def perform_authentication(self, request):
    """
    Perform authentication on the incoming request.

    Note that if you override this and simply 'pass', then authentication
    will instead be performed lazily, the first time either
    `request.user` or `request.auth` is accessed.
    """
    request.user

This method returns request.user. This request is not the original request, dispatch will be assigned to a request Request

@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate()
return self._user

def _authenticate(self):
    """
    Attempt to authenticate the request using each authentication instance
    in turn.
    """
    for authenticator in self.authenticators: 
        # authenicators已经在initialize_request方法中给self定义过了
        try:
            user_auth_tuple = authenticator.authenticate(self) # 执行认证类中的方法 认证
        except exceptions.APIException:
            self._not_authenticated() # 报错就执行这个方法
            raise

        if user_auth_tuple is not None: # 如果上面认证方法返回的不是none
            self._authenticator = authenticator # 把认证的类给赋值给self
            self.user, self.auth = user_auth_tuple # 然后把认证返回后的元组 一个user 一个auth
            return

    self._not_authenticated()

Request return (
Request,
parsers self.get_parsers = (),
authenticators = self.get_authenticators (),
Negotiator = self.get_content_negotiator (),
parser_context = parser_context
)
mentioned in the definition of the Request object when authenticate incoming from the above initialize_request , you can see that he is calling a method get_authenticators

def get_authenticators(self):
    """
    Instantiates and returns the list of authenticators that this view can use.
    """
    return [auth() for auth in self.authentication_classes]

Permissions permission
process
DEF check_permissions (Self, Request):
"" "
. Should the Check Request BE IF at The permitted
. Raises Exception IF AN Appropriate IS not permitted at The Request
" ""
for permission in self.get_permissions ():
IF not permission.has_permission (request, self): # has_permission permission authentication method
# If this is to return False certification authority that is not by
self.permission_denied (#
Request, the Message = getattr (permission, 'the Message', None)

def get_permissions(self):
    """
    Instantiates and returns the list of permissions that this view requires.
    """
    return [permission() for permission in self.permission_classes]

class IndexView(APIView):
authentication_classes = [MyAuthentication]
permission_classes = [MyPermission]

def get(self, request, *args, **kwargs):
    ret = {
        "content": "index ok",
        "code": 200,
        "token": request.auth.token
    }
    return JsonResponse(ret)

Frequency throttles

def check_throttles(self, request):
    """
    Check if request should be throttled.
    Raises an appropriate exception if the request is throttled.
    """
    for throttle in self.get_throttles():
        if not throttle.allow_request(request, self):
            self.throttled(request, throttle.wait())

The method used to acquire get_throttles specified class, then the method performs allow_request

Guess you like

Origin www.cnblogs.com/beichen123/p/11925722.html