惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
Check Point Blog
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Secure Thoughts
Recorded Future
Recorded Future
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
The Blog of Author Tim Ferriss
B
Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Google DeepMind News
Google DeepMind News
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
Arctic Wolf
T
The Exploit Database - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
AWS News Blog
AWS News Blog
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
Google Online Security Blog
Google Online Security Blog
T
Troy Hunt's Blog
I
InfoQ
L
LINUX DO - 热门话题
WordPress大学
WordPress大学
C
Cisco Blogs
G
GRAHAM CLULEY
The Register - Security
The Register - Security
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Schneier on Security
Schneier on Security
Project Zero
Project Zero
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Privacy & Cybersecurity Law Blog
Cloudbric
Cloudbric
H
Hacker News: Front Page
小众软件
小众软件
雷峰网
雷峰网
The Hacker News
The Hacker News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Tor Project blog
博客园 - 聂微东
N
Netflix TechBlog - Medium
V
Vulnerabilities – Threatpost
The GitHub Blog
The GitHub Blog
腾讯CDC
P
Palo Alto Networks Blog
Scott Helme
Scott Helme

郑文峰的博客

使用dify对接飞书多维表格 使用n8n对接飞书多维表格 服务启动时出现 OOM 一次服务升级时pg表DDL执行超时失败 Go语言高效IO缓冲技术详解 Go语言延迟初始化(Lazy Initialization)最佳实践 Go语言字符串拼接性能对比与优化指南 Go语言结构体内存对齐完全指南 Go语言空结构体:零内存消耗的高效编程 Go语言堆栈分配与逃逸分析深度解析 Go语言原子操作完全指南 Go语言内存预分配完全指南 Go语言不可变数据共享:无锁并发编程实践 Go语言零拷贝技术完全指南 Go语言遍历性能深度解析:从原理到优化实践 Go语言Interface Boxing原理与性能优化指南 Go协程池深度解析:原理、实现与最佳实践 使用etcd分布式锁导致的协程泄露与死锁问题 基于pre-commit的Python代码规范落地实践 初识 MCP Server pulsar阻塞导致logstash无法接入日志 django-prometheus使用及源码分析 kube-proxy源码分析 kubernetes service如何通过iptables转发 tcp缓存引起的日志丢失 django-apschedule定时任务异常停止 理解calico容器网络通信方案原理 理解flannel的三种容器网络方案原理 理解Linux IPIP隧道 理解VXLAN网络 理解Linux TunTap设备 快速了解iptables kafka中listener和advertised.listeners的作用 django rest_framework 分页 django后端服务、logstash和flink接入VictoriaMetrics指标监控 python中import原理 docker容器单机网络 手动实现docker容器bridge网络模型 mysql之MVCC原理 mysql之日志 使用java开发logstash的filter插件 使用python实现单例模式的三种方式 redis之缓存 redis之分片集群 redis之哨兵机制 redis之主从库同步 redis之持久化 redis之五种基本数据类型 go中如何处理error pod中将代码与运行环境分离 ddt源码分析 python装饰器的使用方法 读书笔记:如何阅读一本书 使用ddt实现unittest的参数化测试 使用kubeadm安装k8s 优化gin表单的错误提示信息 gin中validator模块的源码分析 go简单使用grpc python简单使用grpc k8s之PV、PVC和StorageClass k8s之StatefulSet k8s之DaemonSet k8s之Job和CronJob k8s之ConfigMap和Secret k8s之Service k8s之Pod k8s之Deployment 容器的本质 docker容器 python迭代器与生成器 python元编程 python垃圾回收机制 python上下文管理器 django rest_framework使用jwt django rest_framework异常处理 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 Flask使用flask_socketio实现websocket flask结合mongo tornado 文件上传 tornado 使用jwt完成用户异步认证 tornado 用户密码 bcrypt加密 tornado 结合wtforms使用表单操作 tornado finish和write区别 tornado 使用peewee-async 完成异步orm数据库操作 pyspark streaming简介 和 消费 kafka示例 使用hue创建ozzie的pyspark action workflow count的性能优化 django rest_framework Authentication django celery 结合使用 网站
django rest_framework 自定义文档
zhengwenfeng · 2022-08-10 · via 郑文峰的博客

# 简介

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_linkAutoSchema中的函数. 重写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