繁体   English   中英

Django 如何在作为所有其他视图父级的类基视图中使用 drf-yasg 生成 swagger 文档?

[英]Django How to use drf-yasg in class-base view which is parent of all other views to generate swagger docs?

我正在为 swagger 文档使用drf-yasg ,但我使用的是BaseView ,它是所有其他视图的父 class 视图,因此所有HTTP方法都是在BaseView中编写的,因此子视图不需要实现这些方法。

问题是,当我将@swagger_auto_schema添加到 baseView 方法时,它没有看到子属性,而是BaseView的属性是空的。

BaseView

class BaseView(APIView):
        model = models.Model
        serializer_class = serializers.Serializer
        description = ''
        id = openapi.Parameter('id', in_=openapi.IN_QUERY, type=openapi.FORMAT_UUID)
    @swagger_auto_schema(manual_parameters=[id] ,responses={200: serializer_class},operation_description=description)
    def get(self, request, id=None, **kwargs):
                ....
    @swagger_auto_schema(request_body=serializer_class)
    def post(self, request, **kwargs):
                ....

然后假设我有这个子视图:

class TestApi(BaseView):
    model = test
    description = 'This is test api'
    serializer_class = TestSerializer

在这种方法中,Swagger显示 description 和serializer_class的空值,因为它看不到子值如何解决这个问题,而不必使用HTTP方法和@swagger_auto_schema配置每个视图?

提前致谢。

  1. 创建一个 python 名为 api_docs.py 的文件,并写下您的 API 查看所有方法的说明。

    docs = { '查看名称': { 'post': '你的描述', 'list': '....description', } }

  2. 之后你必须将它导入你的视图并添加它。

    从 django.utils.decorators 导入 method_decorator

    @method_decorator(name="HTTP 方法名就像post put destroy", decorator=swagger_auto_schema( tags=["App name"], operation_description=docs['ViewName']['post']))

  3. 如果您要覆盖任何方法,那么您必须像这样显式添加该视图

@swagger_auto_schema(tags=["App name"], operation_description=docs['View Name']['post'])

def create(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM