排除特定HTTP方法的swagger文档

问题描述 投票:0回答:2

我使用drf-yasg为我的Django REST API生成swagger文档。我有几个端点,项目/使用GET,POST和DELETE方法;和items / <uuid:itemID>仅限DELETE方法。但是,生成的swagger文档错误地包括后端点的GET和POST。

这是我在urls.py中的一个片段:

urlpatters = [
    url(r'^items/$', views.ItemViewSet.as_view()),
    path('items/<uuid:itemID>', views.ItemViewSet.as_view()),
]

views.py包含类似的内容:

class ItemViewSet(mixins.DestroyModelMixin, GenericAPIView):
    def get(self, request):
            # ...
            return Response(HTTP_200_OK)

    def post(self, request):
            # ...
            return Response(status=status.HTTP_201_CREATED)

    def delete(self, request, itemID):
             # ...
             return Response(status=status.HTTP_204_NO_CONTENT)

    def delete(self, request):
            # ...
            return Response(status=status.HTTP_204_NO_CONTENT)

如何从items / <uuid:itemID>文档中排除GET和POST?

我读过https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rstExclude URLs from Django REST Swagger,但尚未找到有效的解决方案。

django swagger drf-yasg
2个回答
0
投票

我的hackish解决方案:

class SwaggerAutoSchemaMethodExclusion(SwaggerAutoSchema):
    read_op_counter = 0
    create_op_counter = 0       

    def get_operation(self, operation_keys):
        if "create" in in operation_keys:
            SwaggerAutoSchemaMethodExclusion.create_op_counter += 1
            if SwaggerAutoSchemaMethodExclusion.create_op_counter % 2 == 0:
                return None
        elif "read" in operation_keys:
            SwaggerAutoSchemaMethodExclusion.read_op_counter += 1
            if SwaggerAutoSchemaMethodExclusion.read_op_counter % 2 == 0:
                return None

        return super().get_operation(operation_keys)


class ItemViewSet(mixins.DestroyModelMixin, GenericAPIView):
    swagger_schema = SwaggerAutoSchemaMethodExclusion
    // ...

0
投票

您可以通过在views.py中设置swagger_schema = None来从文档中排除和API端点

  class MyView(generics.ListCreateAPIView):
    """MyView class doc."""
    swagger_schema = None

    def get(self, response):
        # Do stuff here

资料来源:https://github.com/axnsan12/drf-yasg/commit/a211184478e6f0ca348312438c9c29d7b535b0fa

© www.soinside.com 2019 - 2024. All rights reserved.