【问题标题】:How to group swagger API endpoints (Function Based Views) with drf_yasg - Django如何使用 drf_yasg 对 swagger API 端点(基于函数的视图)进行分组 - Django
【发布时间】:2021-04-27 04:46:58
【问题描述】:

我正在从 Django 1.11 --> 3.1.5 做一些迁移工作

以前使用“rest_framework_swagger”,我可以在 url.py 中通过这个来完成 swagger api 分组

url(r'^api/v9/test_token1$', 
    api.test_token, 
    name='test_token'),

url(r'^api/v9/test_token2$', 
    api.test_token, 
    name='test_token'),

并得到这个(注意它分组 v9)

但是,我在 Django 3.1.5 上尝试过使用“drf_yasg” url.py

path('/v2/token_api1', token_api1, name='token_api1'),
path('/v2/token_api2', token_api2, name='token_api2'),

我的 api 定义(请注意我使用的是@api_view)

token = openapi.Parameter('token', openapi.IN_FORM, type=openapi.TYPE_STRING, required=True)
@swagger_auto_schema(
    method="post",
    manual_parameters=[token],
    operation_id="token_api1"
)
@api_view(['POST'])
# this is optional and insures that the view gets formdata
@parser_classes([FormParser])
def token_api1(request):
    token = request.POST['token']    
    return Response("success test_api:" + token, status=status.HTTP_200_OK)


token = openapi.Parameter('token', openapi.IN_FORM, type=openapi.TYPE_STRING, required=True)
@swagger_auto_schema(
    method="post",
    manual_parameters=[token],
    operation_id="token_api2"
)
@api_view(['POST'])
# this is optional and insures that the view gets formdata
@parser_classes([FormParser])
def token_api2(request):
    token = request.POST['token']
    return Response("success test_api:" + token, status=status.HTTP_200_OK)   

但是,我明白了(注意到 v2 没有分组)。而且当我进行测试时,也有错误。 (代码 404 错误:未找到)

如何将这些分组到 drf_yasg 中的 API 并确保没有错误? 注意如果url.py是这样的,没有错误但没有分组

path('token_api1', token_api1, name='token_api1'),
path('token_api2', token_api2, name='token_api2'),

【问题讨论】:

标签: django django-rest-framework swagger drf-yasg redoc


【解决方案1】:

name 用于从您的 Django / Python 代码访问端点。所以我相信新版本的 Django 禁止重名。

您可以通过在tags 下为端点提供相同的标签来对端点进行分组。像这样:

@swagger_auto_schema(tags=["my_custom_tag"], auto_schema=NoPagingAutoSchema, filter_inspectors=[DjangoFilterDescriptionInspector])
@action(detail=False, methods=['get'])
def action1(self, request):
    pass


@swagger_auto_schema(tags=["my_custom_tag"], method='delete', manual_parameters=[openapi.Parameter(
    name='delete_form_param', in_=openapi.IN_FORM,
    type=openapi.TYPE_INTEGER,
    description="this should not crash (form parameter on DELETE method)"
)])
@action(detail=True, methods=['delete'])
def action2(self, request, slug=None):
    pass

请注意,您还可以为每个功能提供多个标签,因此它们将显示在几个不同的类别(或组)中。

结果:

【讨论】:

  • 非常感谢@Yuval,另一个很好的答案!
【解决方案2】:

只需使用 @swagger_auto_schema(tags=['tag_name']) 装饰您的视图 swagger_auto_schema 可以用from drf_yasg.utils import swagger_auto_schema导入

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-28
    • 2021-07-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多