2

我使用drf-yasg为我的 Django REST API 生成 swagger 文档。我有几个端点,items/带有 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.rst从 Django REST Swagger 中排除 URL,但尚未找到可行的解决方案。

4

3 回答 3

1

swagger_schema = None您可以通过在您的 views.py 中设置来从文档中排除 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

于 2019-05-17T13:38:28.813 回答
0

我的骇人听闻的解决方案:

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
    // ...
于 2019-03-12T06:20:11.543 回答
0

如果您使用 ViewSet(不是 APIView),则可以使用 @action 装饰器 https://drf-yasg.readthedocs.io/en/stable/custom_spec.html

在我的项目中

class MyEntityViewSet(ModelViewSet):

@swagger_auto_schema(tags=['your tag here'])
@action(methods=['get'], detail=False)
def list(self, request):
    list obtaining code here

@swagger_auto_schema(tags=['your tag here'])
@action(methods=['post'], detail=True)
def create(self, request):
    creation code here

@swagger_auto_schema(tags=['your tag here'], method='delete')
@action(methods=['delete'], detail=True)
def destroy(self, request, entity_id, **kwargs):
    deletion code here 
#same with update

然后在 urls 文件中:

path('my-api/', MyEntityViewSet.as_view({'get': 'list', 'post': 'create'})),
path('my-api/<int:entity_id>/', MyEntityViewSet.as_view({'put': 'update', 'delete': 'destroy'})),
于 2021-08-24T20:03:25.780 回答