drf总流程链接

https://www.cnblogs.com/daviddd/p/11918405.html

drf之权限认证

'''
承接总流程5.3的权限控制
权限认证:实例化每一个权限类得到一个对象列表,循环权限对象列表,执行每一个权限对象的
has_permession方法,返回true或者false,true表示通过权限认证,false表示没有通过,并抛出异常
'''

class APIView(View):

    # 配置文件
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
    settings = api_settings



    def initial(self, request, *args, **kwargs):
        """
        Runs anything that needs to occur prior to calling the method handler.
        """

        # 5.3 权限认证
        self.check_permissions(request)


    # 执行check_permissionds 函数,循环每一个权限对象,进行权限认证处理
    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        # 5.31
        for permission in self.get_permissions():
            if not permission.has_permission(request, self):
                self.permission_denied(
                    request, message=getattr(permission, 'message', None)
                )


    # 5.32 实例化权限类,得到权限对象列表
    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        return [permission() for permission in self.permission_classes]


    # 5.33判断是否权限通过
    def has_permission(self, request, view):
        """
        Return `True` if permission is granted, `False` otherwise.
        """
        # 通过,有权限
        return True

        #如果return False,执行5.34的permission_denied函数,见60行,抛出异常
        return False



    def has_object_permission(self, request, view, obj):
        """
        Return `True` if permission is granted, `False` otherwise.
        """
        return True

    # 5.34抛出异常
    def permission_denied(self, request, message=None):
        """
        If request is not permitted, determine what kind of exception to raise.
        """
        if request.authenticators and not request.successful_authenticator:
            raise exceptions.NotAuthenticated()
        raise exceptions.PermissionDenied(detail=message)
    
01-13 22:24