19 自动生成接口文档

-前后端分离的项目,前端和后端是两拨人写
-纯手写(word,md)---》git
-第三方平台(收费,免费),在平台录入
-公司自己搭建(公司自己开发),录入,直接批量导入
-补充:postman测试接口(导出,导入)
-自动生成接口文档(coreapi,swagger)

自动生成接口文档

1 安装:pip install coreapi

pip install coreapi

2 在主路由中配置

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

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

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

class BookListView(generics.ListAPIView):
            """
            返回所有图书信息.
            """

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

class BookListCreateView(generics.ListCreateAPIView):
            """
            get:
            返回所有图书信息.
            post:
            新建图书.
            """

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

class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
        """
        list:
        返回图书列表数据
        retrieve:
        返回图书详情数据
        latest:
        返回最新的图书数据
        read:
        修改图书的阅读量
        """

如果遇到报错

 

 

#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
}

4. 访问接口文档网页

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

 

 

两点说明:

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

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

class Student(models.Model):
    ...
    age = models.IntegerField(default=0, verbose_name='年龄', help_text='年龄')
    ...

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = "__all__"
        extra_kwargs = {
            'age': {
                'required': True,
                'help_text': '年龄'
            }
        }




自己搭建一个Yapi:https://zhuanlan.zhihu.com/p/366025001


docker-compose部署Yapi

 
posted @ 2022-02-07 21:52  甜甜de微笑  阅读(63)  评论(0编辑  收藏  举报