gpt4 book ai didi

django - Django REST框架Swagger 2.0

转载 作者:行者123 更新时间:2023-12-03 13:29:55 26 4
gpt4 key购买 nike

难以配置Swagger UI
这是非常说明性的文档:https://django-rest-swagger.readthedocs.io/en/latest/

不建议使用YAML文档字符串。有人知道如何从python代码中配置Swagger UI吗?还是应将哪个文件更改为对api端点进行分组,向每个端点添加注释,在Swagger UI中添加查询参数字段?

最佳答案

这是我设法做到的方式:

基本urls.py

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


api.urls.py

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

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来创建自定义数据。

关于django - Django REST框架Swagger 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38542690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com