首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Django REST Swagger中生成响应消息列表?

如何在Django REST Swagger中生成响应消息列表?
EN

Stack Overflow用户
提问于 2016-10-21 19:23:09
回答 1查看 8.5K关注 0票数 26

我昨天已经将Django REST Framework升级到了3.5.0,因为我需要更好的模式生成。

我正在使用API REST Swagger来记录我的,但是不知道如何列出端点提供的所有可能的响应消息。

似乎可以自动生成与我的端点正在执行的操作相对应的成功消息。

因此POST操作生成201响应代码,没有任何描述。

我该如何着手添加我的端点提供的所有响应消息,并为它们提供一些描述?

我正在使用

djangorestframework==3.5.0

django-rest-swagger==2.0.7

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-02 20:52:50

啊,终于明白了。

但!这是hack -可能drf + drf swagger不支持它;基本上问题不是连接到drf和drf swagger代码,而是openapi编解码器,看看你自己:

代码语言:javascript
复制
def _get_responses(link):
    """
    Returns minimally acceptable responses object based
    on action / method type.
    """
    template = {'description': ''}
    if link.action.lower() == 'post':
        return {'201': template}
    if link.action.lower() == 'delete':
        return {'204': template}
    return {'200': template}

上面的代码可以在:openapi_codec/encode.py - github上找到,这没有以任何方式与drf或drf swagger连接-只是为每个链接(例如: GET /api/v1/test/)创建一个空描述的模板。

当然,有可能克服这个问题。但正如我所说的-这是hack on hack :)我将与你分享一个例子:

docs_swagger.views.py

代码语言:javascript
复制
from rest_framework import exceptions
from rest_framework.permissions import AllowAny
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_swagger import renderers

from docs_swagger.schema_generator import CustomSchemaGenerator


def get_swagger_view(title=None, url=None):
    """
    Returns schema view which renders Swagger/OpenAPI.

    (Replace with DRF get_schema_view shortcut in 3.5)
    """
    class SwaggerSchemaView(APIView):
        _ignore_model_permissions = True
        exclude_from_schema = True
        permission_classes = [AllowAny]
        renderer_classes = [
            CoreJSONRenderer,
            renderers.OpenAPIRenderer,
            renderers.SwaggerUIRenderer
        ]

        def get(self, request):
            generator = CustomSchemaGenerator(title=title, url=url)  # this is altered line
            schema = generator.get_schema(request=request)
            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema   Document'
                )
            return Response(schema)

    return SwaggerSchemaView.as_view()

我在CustomSchemaGenerator中做的事情如下:

docs_swagger.schema_generator.py

代码语言:javascript
复制
import urlparse
import coreapi
from rest_framework.schemas import SchemaGenerator

from openapi_codec import encode


def _custom_get_responses(link):
    detail = False
    if '{id}' in link.url:
        detail = True
    return link._responses_docs.get(
        '{}_{}'.format(link.action, 'list' if not detail else 'detail'),
        link._responses_docs
    )


# Very nasty; Monkey patching;
encode._get_responses = _custom_get_responses


class CustomSchemaGenerator(SchemaGenerator):

    def get_link(self, path, method, view):
        """
        Return a `coreapi.Link` instance for the given endpoint.
        """
        fields = self.get_path_fields(path, method, view)
        fields += self.get_serializer_fields(path, method, view)
        fields += self.get_pagination_fields(path, method, view)
        fields += self.get_filter_fields(path, method, view)

        if fields and any([field.location in ('form', 'body') for field in fields]):
            encoding = self.get_encoding(path, method, view)
        else:
            encoding = None

        description = self.get_description(path, method, view)

        if self.url and path.startswith('/'):
            path = path[1:]

        # CUSTOM
        data_link = coreapi.Link(
            url=urlparse.urljoin(self.url, path),
            action=method.lower(),
            encoding=encoding,
            fields=fields,
            description=description
        )

        data_link._responses_docs = self.get_response_docs(path, method, view)

        return data_link

    def get_response_docs(self, path, method, view):
        return view.responses_docs if hasattr(view, 'responses_docs') else {'200': {
            'description': 'No response docs definition found.'}
        }

最后:

my_view.py

代码语言:javascript
复制
class TestViewSet(viewsets.ModelViewSet):
    queryset = Test.objects.all()
    serializer_class = TestSerializer

    responses_docs = {
        'get_list': {
            '200': {
                'description': 'Return the list of the Test objects.',
                'schema': {
                    'type': 'array',
                    'items': {
                        'type': 'object',
                        'properties': {
                            'id': {
                                'type': 'integer'
                            }
                        }
                    }
                }
            },
            '404': {
                'description': 'Not found',
                'schema': {
                    'type': 'object',
                    'properties': {
                        'message': {
                            'type': 'string'
                        }
                    }
                },
                'example': {
                    'message': 'Not found.'
                }
            }
        },
        'get_detail': {
            '200': {
                'description': 'Return single Test object.',
                'schema': {
                    'type': 'object',
                    'properties': {
                        'id': {
                            'type': 'integer'
                        }
                    }
                }
            },
            '404': {
                'description': 'Not found.',
                'schema': {
                    'type': 'object',
                    'properties': {
                        'message': {
                            'type': 'string'
                        }
                    }
                },
                'example': {
                    'message': 'Not found.'
                }
            }
        }
    }

我认为这更像是一种乐趣,而不是真正的解决方案。在当前状态下,真正的解决方案可能是不可能实现的。也许你应该问问drf swagger的创建者--他们有支持响应的计划吗?

无论如何,swagger UI:

快乐编码:)

票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40175410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档