Django休息swagger_auto_schema自定义响应体

时间:2018-03-23 20:21:35

标签: django django-rest-framework swagger

我已经从django rest viewset重写了list函数来自定义响应体(它返回了一个json数组,我想返回一个包含该数组的对象) 我想把这个回应放在swagger doc中!我在django中使用drf_yasg app。 我写了这段代码:

from drf_yasg.openapi import Schema, TYPE_OBJECT, TYPE_STRING, TYPE_ARRAY
from drf_yasg.utils import swagger_auto_schema
class StudentViewSet(viewsets.ModelViewSet):
    @swagger_auto_schema(responses={200: Schema(type=TYPE_OBJECT)})
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response({'students': serializer.data})

我不知道如何将我的响应对象描述提供给Schema对象。我搜索了这么多,但我没有发现任何有用的东西!

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

@swagger_auto_schema(responses={
    status.HTTP_200_OK: Schema(
        type=TYPE_OBJECT,
        properties={
           'students': Schema(
              type=TYPE_ARRAY
           )
        }
    )
})

答案 1 :(得分:0)

首先导入这些包/模块。

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework import status

下面的代码在函数视图的正上方用作装饰器

login_schema = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'usernmae': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
        'password': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
    },
    required=['username', 'password']
)
login_schema_response = {
    status.HTTP_200_OK: openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
           'students': openapi.Schema(type=openapi.TYPE_OBJECT)
        }
    ),
    status.HTTP_201_CREATED: openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
           'students': openapi.Schema(type=openapi.TYPE_OBJECT)
        }
    ),
}

@swagger_auto_schema(method='post', request_body=login_schema, responses = login_schema_response)
def myAccount(request):
     pass

在这里,我将请求和响应架构对象存储在不同的变量中。