我有一个用于API POST
/api/samples/sample_id/check
的视图集SampleViewSet。我为它定义了对象级别权限。
class SamplePermission(BasePermission):
def has_object_permission(self, request, view, obj):
return True
class SampleViewSet(viewsets.ModelViewSet):
permission_classes = (SamplePermission, )
@detail_route(methods=['post'])
def check(self, request, pk=None):
if pk:
print "check"
调用API POST
/api/samples/check
时,未调用函数has_object_permission。可能是什么原因?
答案 0 :(得分:1)
权限不起作用,因为方法check_object_permissions
在get_object
函数中调用。因此,您应该在check
函数中调用其中一个函数:
@detail_route(methods=['post'])
def check(self, request, pk=None):
obj = self.get_object()
....
或者您可以直接在detail_route
@detail_route(
permission_classes=[SamplePermission],
methods=['post'])
def check(self, request, pk=None):
...