Exclude swagger docs for specific HTTP methods

戏子无情 提交于 2019-12-25 02:32:50

问题


I use drf-yasg to generate swagger docs for my Django REST API. I have a couple of endpoints, items/ with GET, POST and DELETE methods; and items/<uuid:itemID> with DELETE method only. However, the generated swagger docs erroneously include also GET and POST for the latter endpoint.

This is a snippet of what I have in urls.py:

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

views.py contains something like:

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)

How can I exclude GET and POST from items/<uuid:itemID> documentation?

I have read through https://github.com/axnsan12/drf-yasg/blob/master/docs/custom_spec.rst and Exclude URLs from Django REST Swagger but haven't found a working solution yet.


回答1:


My hackish solution:

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
    // ...



回答2:


You can exclude and API endpoint from the documentation by setting the swagger_schema = None in your views.py

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

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

Source: https://github.com/axnsan12/drf-yasg/commit/a211184478e6f0ca348312438c9c29d7b535b0fa



来源:https://stackoverflow.com/questions/52813253/exclude-swagger-docs-for-specific-http-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!