django 如何从drf-spectual API文档中删除RetrieveUpdateAPIView中的put方法?

dluptydi  于 2023-01-21  发布在  Go
关注(0)|答案(3)|浏览(144)

我有以下看法:

class PersonalInfos(generics.RetrieveUpdateAPIView):
    serializer_class = ClientSerializer
    permission_classes = [IsAuthenticated]
    def get_queryset(self):
        """
        :return: A QuerySet Object
        """
        return Client.objects.get(user=self.request.user)

    def get(self, *args):
        """
        :param args: Handled by rest_framework views.dispatch

        :return: JSON object containing User Personal Data
        """
        queryset = self.get_queryset()
        serializer = ClientSerializer(queryset)
        return Response(data=serializer.data)

    def patch(self, request):
        """
        :param request: request object is sent by the client

        :return:  Json response with the data sent of the body
        """

        client = self.get_queryset()
        serializer = ClientSerializer(client, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data, status=200)
        return Response(data="Unexpected Parameters", status=400)

视图中一切正常,但问题是我正在使用drf-spectual,它在文档中向我显示了一个PUT方法,而我们在API中并不需要该方法。我的问题是,如何定制drf-spectual,使其不在文档中包含PUT方法?

5n0oy7gb

5n0oy7gb1#

您可以使用@extend_schema装饰器从生成的模式中排除一个或多个方法,如下所示。

@extend_schema(methods=['PUT'], exclude=True)
20jt8wwn

20jt8wwn2#

我使用RetrieveAPIView而不是UpdateRetrieveAPIView解决了这个问题,我用扩展了它,使其包含了一个PATCH方法。RetrieveAPIView将完美地处理PATCH方法,并且不会在API文档中自动显示UPDATE请求。

class PersonalInfos(generics.RetrieveAPIView):
    serializer_class = ClientSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """
        :return: A QuerySet Object
        """
        return Client.objects.get(user=self.request.user)

    def get(self, *args):
        """
        :param args: Handled by rest_framework views.dispatch

        :return: JSON object containing User Personal Data
        """
        queryset = self.get_queryset()
        serializer = ClientSerializer(queryset)
        return Response(data=serializer.data)

    def patch(self, request):
        """
        :param request: request object is sent by the client

        :return:  Json response with the data sent of the body
        """

        client = self.get_queryset()
        serializer = ClientSerializer(client, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data, status=200)
        return Response(data="Unexpected Parameters", status=400)
cbjzeqam

cbjzeqam3#

这应该排除drf-yasg中的put方法

class MyView(generics.RetrieveUpdateAPIView):

    @swagger_auto_schema(auto_schema=None)
    def put(self, request, *args, **kwargs):
        return

资料来源:https://drf-yasg.readthedocs.io/en/stable/custom_spec.html#excluding-endpoints

相关问题