郑文峰的博客 郑文峰的博客
首页
  • python之路
  • go之路
  • 其他
  • redis
  • mysql
  • docker
  • k8s
读书破万卷
周刊
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)

zhengwenfeng

穷则变,变则通,通则久
首页
  • python之路
  • go之路
  • 其他
  • redis
  • mysql
  • docker
  • k8s
读书破万卷
周刊
关于
  • 导航 (opens new window)
  • 代码片段 (opens new window)
  • 收藏
  • 友链
  • 外部页面

    • 开往 (opens new window)
  • 索引

    • 分类
    • 标签
    • 归档
GitHub (opens new window)
  • python

    • 基础

    • 第三方库

    • django

      • django celery 结合使用
      • django rest_framework使用jwt
      • django rest_framework Authentication
      • django rest_framework异常处理
      • django rest_framework 自定义文档
        • 简介
        • 配置
        • 自定义文档
        • schema
          • 方法一
          • 方法二
        • location
      • django压缩文件下载
      • django rest_framework使用pytest单元测试
      • django restframework choice 自定义输出数据
      • django Filtering 使用
      • django viewset 和 Router 配合使用时报的错
      • django model的序列化
      • django中使用AbStractUser
      • django.core.exceptions.ImproperlyConfigured Application labels aren't unique, duplicates users
      • django 中 media配置
      • django 外键引用自身和on_delete参数
      • django 警告 while time zone support is active
      • django rest_framework 分页
    • flask

    • tornado

    • 其他

  • go

  • 其他

  • 编程
  • python
  • django
zhengwenfeng
2022-08-10
目录

django rest_framework 自定义文档

# 简介

django rest_framework 自动生成文档的功能,能够很好的给前端提供帮助,在文档中可以看到api的参数和其提供的功能信息,并且还能够在上面直接测试api接口。

官网 (opens new window)

# 配置

urls.py

from rest_framework.documentation import include_docs_urls

urlpatterns = [
    ...
    url(r'^docs/', include_docs_urls(title='My API title'))]
1
2
3
4
5

即可使用该url对文档的访问

# 自定义文档

虽然可以自动生成文档,但是不是很完善,所以需要自定义写文档。

# schema

通过改写AutoSchema来完成自定义文档。

# 方法一

get_link是AutoSchema中的函数. 重写get_link函数,对文档中的每个字段的说明进行改写。

集成AutoSchema,在__init__初始化params_desc_dict参数,该参数包含文档中字段对应的注释,然后在get_link对该参数进行解析,并替换字段注释.

class BaseSchema(AutoSchema):
    """
    自动生成的文档会有缺失,或者是因为可读性比较差。所以需要对文档中的字段进行自定义注解。
    该类是通用的对文档中的get、post、put、delete、patch进行注释。
    是在已有字段的基础上修改注释.
    
    `get`是对get中的字段进行注解说明。
    `other`是`post`、`put`、`delete`、`patch`
    
    例子:
        {
            "get": {
                "字段名": "对该字段进行注释"
            },
            "post": {
                "字段名": "对该字段进行注释"
            }
        }

    """
    def __init__(self, manual_fields=None, params_desc_dict=None):
        self.params_desc_dict = {
            "get": {
                "page": "当前页码",
                "page_size": "每一页显示的行数. 默认传 10条"
            },
            "other": {

            }
        }

        if params_desc_dict:
            if 'get' in params_desc_dict:
                self.params_desc_dict['get'].update(params_desc_dict['get'])

            if 'other' in params_desc_dict:
                self.params_desc_dict['other'].update(params_desc_dict['other'])

        super(BaseSchema, self).__init__(manual_fields)

    def get_link(self, path, method, base_url):
        link = super(BaseSchema, self).get_link(path, method, base_url)

        fields = []

        params_method = 'get' if method.lower() == 'get' else 'other'

        for field in link.fields:
            if field.name in self.params_desc_dict[params_method].keys():
                field = field._replace(
                    schema=coreschema.String(description=self.params_desc_dict[params_method][field.name]))

            fields.append(field)

        return coreapi.Link(
            url=link.url,
            action=link.action,
            encoding=link.encoding,
            fields=fields,
            description=link.description
        )

periodictaskSchema = BaseSchema(params_desc_dict={
    'other': {
        "crontab": "定时crontab. json。 包含的字段有: minute, hour, day_of_week, day_of_month, month_of_year",
        "name": "该定时任务名称",
        "task": "模板任务名",
        "args": "传递给任务模板参数. 数组",
        "kwargs": "传递给任务模板参数. json字符串",
        "queue": "将任务放在哪个队列中.",
        "enabled": "是否开启该任务. True or False. 默认为True",
        "description": "定时任务说明"
    }
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

在view中绑定自定义的schema

class PeriodictasksViewSet(viewsets.ModelViewSet):
    queryset = PeriodicTask.objects.all()
    serializer_class = PeriodictaskSerializer
    schema = periodictaskSchema
1
2
3
4

# 方法二

如果只是普通的APIView的话,直接在AutoSchema中添加字段即可。

databaseInfoSchema = AutoSchema(manual_fields=[
    coreapi.Field(name="db", required=True, location="query",
                  schema=coreschema.String(description="数据库host, normal或者sub")),
    coreapi.Field(name="database", location="query", schema=coreschema.String(description="数据库")),
    coreapi.Field(name="table", required=True, location="query", schema=coreschema.String(description="数据库表"))
])
1
2
3
4
5
6

绑定自定义schema

class DataBaseInfo(APIView):
    schema = databaseInfoSchema

    def get(self, request):
        pass
1
2
3
4
5

# location

location 描述
query 查询. list
form 表单提交. post
path 在url中的,/oozieJob/{id}/. read
#python#django
上次更新: 2023/01/15, 15:47:48
django rest_framework异常处理
django压缩文件下载

← django rest_framework异常处理 django压缩文件下载→

最近更新
01
django rest_framework 分页
03-20
02
学习周刊-第03期-第09周
03-03
03
学习周刊-第02期-第08周
02-24
更多文章>
Theme by Vdoing | Copyright © 2022-2023 zhengwenfeng | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式