DRF权限

权限的源码

 # APIView --->dispatch ---> initial ---> self.perform_authentication(request)(APIView的对象方法)
    def check_permissions(self, request):
        """
        Check if the request should be permitted.
        Raises an appropriate exception if the request is not permitted.
        """
        # 遍历权限对象列表得到一个个权限对象(权限器),进行权限认证
        for permission in self.get_permissions():
            # 权限类一定有一个has_permission权限方法,用来做权限认证的
            # 参数:权限对象self、请求对象request、视图类对象
            # 返回值:有权限返回True,无权限返回False
            if not permission.has_permission(request, self):
                self.permission_denied(
                    request,
                    message=getattr(permission, 'message', None),
                    code=getattr(permission, 'code', None)
                )

权限的使用

# 写一个类,继承BasePermission,重写has_permission,如果权限通过,就返回True,不通过就返回False
from rest_framework.permissions import BasePermission


class UserPermission(BasePermission):
    def has_permission(self, request, view):
        # 不是超级用户,不能访问
        # 由于认证已经过了,request内就有user对象了,当前登录用户
        user = request.user  # 当前登录用户
        # 如果该字段用了choice,通过get_字段名_display()就能取出choice后面的中文
        print(user.get_user_type_display())
        if user.user_type == 1:
            return True
        else:
            return False
        
# 局部使用
class TestView(APIView):
    permission_classes = [app_auth.UserPermission]

# 全局使用
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": ["app01.app_auth.MyAuthentication", ],
    'DEFAULT_PERMISSION_CLASSES': ["app01.app_auth.UserPermission"],
}

# 局部禁用
class TestView(APIView):
    permission_classes = []

内置权限的使用

# 演示一下内置权限的使用IsAdminUser
# 1 创建超级管理员
# 2 写一个测试视图类
# 演示内置权限 超级管理员可以查看
    from rest_framework.permissions import IsAdminUser
    from rest_framework.authentication import SessionAuthentication

    class TestView3(APIView):
        authentication_classes = [SessionAuthentication]
        permission_classes = [IsAdminUser]

        def get(self, request, *args, **kwargs):
            return Response("这是测试数据2222222  超级管理员可以看")
# 3 超级用户登录到admin,再访问test3就有权限
# 4 正常的话,普通管理员没有权限看(判断的是is_staff字段)
原文地址:https://www.cnblogs.com/ZhZhang12138/p/14875876.html