Django REST框架Swagger 2.0

问题描述 投票:18回答:4

很难配置Swagger UI以下是非常简洁的文档:https://django-rest-swagger.readthedocs.io/en/latest/

YAML文档字符串已弃用。有人知道如何从python代码中配置Swagger UI吗?或者我应该将哪个文件更改为组api端点,为每个端点添加注释,以在Swagger UI中添加查询参数字段?

django django-rest-framework swagger-ui swagger-2.0 openapi
4个回答
9
投票

这就是我设法做到的方式:

base urls.py

urlpatterns = [
...
url(r'^api/', include('api.urls', namespace='api')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
...
]

API.URLs.朋友

urlpatterns = [
url(r'^$', schema_view, name='swagger'),
url(r'^article/(?P<pk>[0-9]+)/$', 
    ArticleDetailApiView.as_view(actions={'get': 'get_article_by_id'}), 
    name='article_detail_id'),
url(r'^article/(?P<name>.+)/(?P<pk>[0-9]+)/$', 
    ArticleDetailApiView.as_view(actions={'get': 'get_article'}), 
    name='article_detail'),
]

api.views.py。在MyOpenAPIRenderer中,我更新数据字典以添加描述,查询字段以及更新类型或所需功能。

class MyOpenAPIRenderer(OpenAPIRenderer):
    def add_customizations(self, data):
        super(MyOpenAPIRenderer, self).add_customizations(data)
        data['paths']['/article/{name}/{pk}/']['get'].update(
            {'description': 'Some **description**',
             'parameters': [{'description': 'Add some description',
                             'in': 'path',
                             'name': 'pk',
                             'required': True,
                             'type': 'integer'},
                            {'description': 'Add some description',
                             'in': 'path',
                             'name': 'name',
                             'required': True,
                             'type': 'string'},
                            {'description': 'Add some description',
                             'in': 'query',
                             'name': 'a_query_param',
                             'required': True,
                             'type': 'boolean'},
                            ]
             })
        # data['paths']['/article/{pk}/']['get'].update({...})
        data['basePath'] = '/api'  

@api_view()
@renderer_classes([MyOpenAPIRenderer, SwaggerUIRenderer])
def schema_view(request):
    generator = SchemaGenerator(title='A title', urlconf='api.urls')
    schema = generator.get_schema(request=request)
    return Response(schema)


class ArticleDetailApiView(ViewSet):

    @detail_route(renderer_classes=(StaticHTMLRenderer,))
    def get_article_by_id(self, request, pk):
        pass

    @detail_route(renderer_classes=(StaticHTMLRenderer,))
    def get_article(self, request, name, pk):
        pass

更新django-rest-swagger(2.0.7):仅使用get_customizations替换add_customizations。

views.朋友

class MyOpenAPIRenderer(OpenAPIRenderer):
    def get_customizations(self):
        data = super(MyOpenAPIRenderer, self).get_customizations()
        data['paths'] = custom_data['paths']
        data['info'] = custom_data['info']
        data['basePath'] = custom_data['basePath']
        return data

您可以阅读swagger specification来创建自定义数据。


7
投票

所以,似乎发生的事情是django-rest-framework qazxsw poop,但它是半生不熟的,并且缺少从代码文档生成动作描述的能力,并且有一个added the new SchemeGenerator,应该是3.5.0。

与此同时,django-rest-swagger继续更新他们的代码以使用新的SchemaGenerator,这使得它现在成为open issue about it

非常奇怪的一系列事件导致了这一点):希望很快就能解决这个问题。目前,建议的答案是唯一的选择。


7
投票

编辑 - 因为swagger版本2.2.0和休息框架3.9.2创建这样的自定义架构:

breaking change

然后,只需使用from rest_framework.schemas import AutoSchema class CustomSchema(AutoSchema): def get_link(self, path, method, base_url): link = super().get_link(path, method, base_url) link._fields += self.get_core_fields() return link def get_core_fields(self): return getattr(self.view, 'coreapi_fields', ()) 设置。

DEFAULT_SCHEMA_CLASS

!以下方法已过时。

由于我找不到任何可行的选项REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'common.schema.CustomSchema', } ,我只是创建了自己的SchemaGenerator,如下所示:

here

创建了一个招摇的视图:

from rest_framework.schemas import SchemaGenerator


class MySchemaGenerator(SchemaGenerator):   
    title = 'REST API Index'

    def get_link(self, path, method, view):
        link = super(MySchemaGenerator, self).get_link(path, method, view)
        link._fields += self.get_core_fields(view)
        return link

    def get_core_fields(self, view):
        return getattr(view, 'coreapi_fields', ())

在urls.py中使用此视图:

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


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 = MySchemaGenerator()
        schema = generator.get_schema(request=request)

        return Response(schema)

在APIView中添加自定义字段:

url(r'^docs/$', SwaggerSchemaView.as_view()),

0
投票

使用提出的解决方案有点hacky但工作正常,实现提议的解决方案可能面临一些问题但是这个文档解释了django rest swagger 2集成以及逐步面临的问题:class EmailValidator(APIView): coreapi_fields = ( coreapi.Field( name='email', location='query', required=True, description='Email Address to be validated', type='string' ), ) def get(self, request): return Response('something')

很晚,但它可能有助于现在寻求帮助的人。

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