Django Rest Framework在某些情况下不允许对视图进行身份验证访问

时间:2018-12-13 16:36:35

标签: python django django-rest-framework

我有一个 ViewSet ,其中permission_classes设置为(permissions.IsAuthenticated,),但是我希望此视图在方法为retrieve()时允许未经身份验证的访问。 / p>

这是我的 ViewSet

class AlbumViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = proxies.AlbumProxy.objects.all()
    serializer_class = serializers.AlbumSerializer
    filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter,)
    search_fields = ('name', 'description', 'company__name')
    filter_fields = ('code', 'company')

    def retrieve(self, request, pk):
        password = request.query_params.get('password', None)

        instance = proxies.AlbumProxy.objects.get(code=pk)

        if instance.access_code != password and password != settings.MASTER_KEY:
            raise Exception(_("Invalid password for album {}".format(instance.code)))

        instance_to_return = serializers.AlbumSerializer(instance=instance, context={'request': request}).data
        instance_to_return.pop('access_code')

        return Response(instance_to_return)

有没有方法可以在方法permission_classes启用时禁用retrieve(),但是在其他情况下仍可以使它工作?

2 个答案:

答案 0 :(得分:0)

您可以像这样覆盖get_permissions:

def get_permissions(self):
    if self.action == 'retrieve':
        return []  # This method should return iterable of permissions
    return super().get_permissions()

答案 1 :(得分:0)

Django Rest Framework开箱即可提供您所需的内容。参见IsAuthenticatedOrReadOnly permission