zoukankan      html  css  js  c++  java
  • DRF-自动生成接口文档

    REST framework可以自动帮助我们生成接口文档。

    接口文档以网页的方式呈现。

    自动接口文档能生成的是继承自APIView及其子类的视图。

    1. 安装依赖

    REST framewrok生成接口文档需要coreapi库的支持

    pip install coreapi

     

    2. 设置接口文档访问路径

    在总路由中添加接口文档路径。

    文档路由对应的视图配置为rest_framework.documentation.include_docs_urls

    参数title为接口文档网站的标题。

    from rest_framework.documentation import include_docs_urls
    
    urlpatterns = [
        ...
        url(r'^docs/', include_docs_urls(title='My REST API'))
    ]

    3. 文档描述说明的定义位置

    1) 单一方法的视图,可直接使用类视图的文档字符串,如

    class DepartmentListView(generics.ListAPIView):
        """
        返回所有部门信息.
        """

    2)包含多个方法的视图,在类视图的文档字符串中,分开方法定义,如

    class DepartmentListCreateView(generics.ListCreateAPIView):
        """
        get:
        返回所有部门信息.
    
        post:
        创建部门.
        """

    3)对于视图集ViewSet,仍在类视图的文档字符串中封开定义,但是应使用action名称区分,如

    class DepartmentViewSet(ListModelMixin, RetrieveModelMixin, GenericViewSet):
        """
        list:
        分页查询部门对象
    
        retrieve:
        查询一个部门信息
    
        latest:
        查询最新添加的部门
    
        name:
        修改部门名称
        """

    两点说明:

    1) 视图集ViewSet中的retrieve名称,在接口文档网站中叫做 read

    2)参数的Description需要在序列化器类的字段中以help_text选项定义,如:

    class DepartmentSerializer(serializers.Serializer):
        ...
        name = serializers.CharField(label='部门名称', max_length=20,
            help_text='部门名称')
        ...
    class DepartmentSerializer2(serializers.ModelSerializer):
        ...
        class Meta:
            ...
            extra_kwargs = {
                'name': {..., 'help_text': '部门名称'}
            }
  • 相关阅读:
    Java学习之路(一)——JDK的下载与安装
    无法将“add-migration”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。解决方案
    VS2019只能提示选中首选项的快捷键切换
    Visual Studio空格变成点的快捷键切换
    Visual Studio 2019 打开即时窗口
    完全卸载node.js
    安装node.js和vue
    在后台启动Redis
    mysql的数据库优化方案
    hadoop
  • 原文地址:https://www.cnblogs.com/chichung/p/9947312.html
Copyright © 2011-2022 走看看