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

    一 自动生成接口文档

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

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

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

    1.1. 安装依赖

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

    1
    pip install coreapi

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

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

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

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

    1
    2
    3
    4
    5
    6
    from rest_framework.documentation import include_docs_urls

    urlpatterns = [
    ...
    path('docs/', include_docs_urls(title='站点页面标题'))
    ]

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

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

    1
    2
    3
    4
    classBookListView(generics.ListAPIView):
    """
    返回所有图书信息.
    """

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

    1
    2
    3
    4
    5
    6
    7
    8
    classBookListCreateView(generics.ListCreateAPIView):
    """
    get:
    返回所有图书信息.

    post:
    新建图书.
    """

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    classBookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    """
    list:
    返回图书列表数据

    retrieve:
    返回图书详情数据

    latest:
    返回最新的图书数据

    read:
    修改图书的阅读量
    """

    1.4. 访问接口文档网页

    浏览器访问 127.0.0.1:8000/docs/,即可看到自动生成的接口文档。

    接口文档网页

    如果遇到报错

    1
    2
    3
    4
    5
    6
    #AttributeError: 'AutoSchema' object has no attribute 'get_link'
    REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    # 新版drf schema_class默认用的是rest_framework.schemas.openapi.AutoSchema

    }

    两点说明:

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

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

    1
    2
    3
    4
    classStudent(models.Model):
    ...
    age = models.IntegerField(default=0, verbose_name='年龄', help_text='年龄')
    ...

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    classStudentSerializer(serializers.ModelSerializer):
    classMeta:
    model = Student
    fields = "__all__"
    extra_kwargs = {
    'age': {
    'required': True,
    'help_text': '年龄'
    }
    }
  • 相关阅读:
    应用实例:用户登录(2009.10.23)
    ASP.NET学习笔记:服务器控件 (2009.11.9)
    小实例:模拟电话簿
    用Iframe实现左边TreeView导航,右边显示相应内容的布局
    HTML&CSS&JaveScript学习笔记(2009.11.19)
    C#中问号(?)的用法
    GridView的简单分页等
    GridView正反双向排序
    代码理解(2009.11.20)
    ASP.NET学习笔记:数据库操作 (2009.11.10)
  • 原文地址:https://www.cnblogs.com/liqiangwei/p/14201065.html
Copyright © 2011-2022 走看看