15

我正在使用 DRF 编写 API。我想为模型视图集中的每个视图赋予不同的权限。我有两组(客户和员工)。我在permissions.py中将它们过滤为 Isstaff 和 Iscustomer 。

class Iscustomer(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user and request.user.groups.filter(name='customers'):
            return True
        return False


class Isstaff(permissions.BasePermission):
    def has_permission(self, request, view):
        if request.user and request.user.groups.filter(name='staff'):
            return True
        return False

我试图覆盖使用get_permissions方法。当我将一个组放入时self.permission_classes,它工作正常。

class cityviewset(viewsets.ModelViewSet):
    queryset = city.objects.all()
    serializer_class = citySerializer

    def get_permissions(self):    
        if self.request.method == 'POST' or self.request.method == 'DELETE':
            self.permission_classes = [Isstaff]
        return super(cityviewset, self).get_permissions()

但是,当我尝试将多个组放入时self.permission_classes,它会失败。

def get_permissions(self):
    if self.request.method == 'POST' or self.request.method == 'DELETE':
        self.permission_classes = [Isstaff,Iscustomer,]
    return super(cityviewset, self).get_permissions()
4

1 回答 1

10

问题是您permission_classes在视图中添加多个。检查您的方法permissionscheck_permissions()。如果您查看 DRF 代码,

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():
        if not permission.has_permission(request, self):
            self.permission_denied(
                request, message=getattr(permission, 'message', None)
            )

当您提供多个权限类时,用户必须同时满足这两个权限。因此,登录用户必须同时是员工和客户。我认为这就是您的观点失败的原因。

于 2017-07-24T12:14:31.107 回答