drf 自动生成接口文档

安装

pip install coreapi

设置接口文档路径

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

文档描述

单一方法的视图

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

多个方法的视图

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

视图集ViewSet

class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
 """
 list:
 返回图书列表数据

 retrieve:
 返回图书详情数据

 latest:
 返回最新的图书数据

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

配置文件

REST_FRAMEWORK = {
    # 匿名
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}

说明

视图集ViewSet中的retrieve名称,在接口文档网站中叫做read
参数的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': '年龄'
            }
        }

image

posted @ 2022-10-07 15:00  Sherwin_szw  阅读(14)  评论(0编辑  收藏  举报