六、权限


返回

6.1 定义权限类

  • utils/permissions.py定义权限类的has_permission方法

    from rest_framework.permissions import BasePermission
    
    
    class MyPermission(BasePermission):
        message = "您没有权限"
    
        def has_permission(self, request, view):
            user_obj = request.user
            # 用户权限的类别
            if user_obj.type == 3:
                return False
            else:
                return True
    
    

6.2 应用局部权限

  • views.py

    from rest_framework.views import APIView
    from utils.auth import MyAuth
    from utils.permission import MyPermission
    
    
    class TestView(APIView):
        authentication_classes = [MyAuth, ]  # 局部认证
        permission_classes = [MyPermission, ]  # 局部权限
    
        def get(self, request):
            pass
            
    

6.3 利用框架

  • 提供了七种权限类

    from rest_framework.permissions import AllowAny
    from rest_framework.permissions import DjangoObjectPermissions
    from rest_framework.permissions import DjangoModelPermissions
    from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
    from rest_framework.permissions import IsAuthenticated
    from rest_framework.permissions import IsAuthenticatedOrReadOnly
    from rest_framework.permissions import IsAdminUser
    
返回