Django(74)drf-spectacular自动生成接口文档
介绍
drf-spectacular
是为Django REST Framework
生成合理灵活的OpenAPI 3.0
模式。它可以自动帮我们提取接口中的信息,从而形成接口文档,而且内容十分详细,再也不用为写接口文档而心烦了
这个库主要实现了3个目标
- 从DRF中提取更多的schema信息
- 提供灵活性,使schema在现实世界中可用(不仅仅是示例)
- 生成一个与最流行的客户端生成器配合良好的schema
环境准备
- Python >= 3.6
- Django (2.2, 3.1, 3.2)
- Django REST Framework (3.10, 3.11, 3.12)
安装
使用pip
命令安装
pip install drf-spectacular
然后在settings.py
的INSTALLED_APPS
安装drf-spectacular
INSTALLED_APPS = [
# ALL YOUR APPS
'drf_spectacular',
]
最后向DRF注册我们壮观的AutoSchema
REST_FRAMEWORK = {
# YOUR SETTINGS
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
drf-spectacular
有健全的默认设置,非常好用开箱即用,不需要指定任何设置,但我们建议至少指定一些元数据
SPECTACULAR_SETTINGS = {
'TITLE': 'API接口文档',
'DESCRIPTION': '项目详情介绍',
'VERSION': '1.0.0',
# OTHER SETTINGS
}
使用方式
我们只需要在urls.py
中添加接口地址即可
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
urlpatterns = [
# YOUR PATTERNS
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
# Optional UI:
path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), # swagger接口文档
path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), # redoc接口文档
]
然后我们启动项目,访问http://127.0.0.1:8000/api/schema/swagger-ui/
,就会出现接口文档
我们可以看到图上有我们之前在settings.py
中配置的TITLE
和DESCRIPTION
和VERSION
,如果想自定义更多的设置,请看文档
自定义接口内容信息
上面我们可以访问swagger
接口文档,但是我们点开接口会发现没有任何内容信息
所以我们还需要在view
视图中,使用装饰器@extend_schema
来制定接口文档中的接口信息
我们先来看下装饰器extend_schema
的源码
def extend_schema(
operation_id: Optional[str] = None,
parameters: Optional[List[Union[OpenApiParameter, _SerializerType]]] = None,
request: Any = empty,
responses: Any = empty,
auth: Optional[List[str]] = None,
description: Optional[str] = None,
summary: Optional[str] = None,
deprecated: Optional[bool] = None,
tags: Optional[List[str]] = None,
exclude: bool = False,
operation: Optional[Dict] = None,
methods: Optional[List[str]] = None,
versions: Optional[List[str]] = None,
examples: Optional[List[OpenApiExample]] = None,
extensions: Optional[Dict[str, Any]] = None,
) -> Callable[[F], F]:
"""
Decorator mainly for the "view" method kind. Partially or completely overrides
what would be otherwise generated by drf-spectacular.
:param operation_id: replaces the auto-generated operation_id. make sure there
are no naming collisions.
:param parameters: list of additional or replacement parameters added to the
auto-discovered fields.
:param responses: replaces the discovered Serializer. Takes a variety of
inputs that can be used individually or combined
- ``Serializer`` class
- ``Serializer`` instance (e.g. ``Serializer(many=True)`` for listings)
- basic types or instances of ``OpenApiTypes``
- :class:`.OpenApiResponse` for bundling any of the other choices together with
either a dedicated response description and/or examples.
- :class:`.PolymorphicProxySerializer` for signaling that
the operation may yield data from different serializers depending
on the circumstances.
- ``dict`` with status codes as keys and one of the above as values.
Additionally in this case, it is also possible to provide a raw schema dict
as value.
- ``dict`` with tuples (status_code, media_type) as keys and one of the above
as values. Additionally in this case, it is also possible to provide a raw
schema dict as value.
:param request: replaces the discovered ``Serializer``. Takes a variety of inputs
- ``Serializer`` class/instance
- basic types or instances of ``OpenApiTypes``
- :class:`.PolymorphicProxySerializer` for signaling that the operation
accepts a set of different types of objects.
- ``dict`` with media_type as keys and one of the above as values. Additionally in
this case, it is also possible to provide a raw schema dict as value.
:param auth: replace discovered auth with explicit list of auth methods
:param description: replaces discovered doc strings
:param summary: an optional short summary of the description
:param deprecated: mark operation as deprecated
:param tags: override default list of tags
:param exclude: set True to exclude operation from schema
:param operation: manually override what auto-discovery would generate. you must
provide a OpenAPI3-compliant dictionary that gets directly translated to YAML.
:param methods: scope extend_schema to specific methods. matches all by default.
:param versions: scope extend_schema to specific API version. matches all by default.
:param examples: attach request/response examples to the operation
:param extensions: specification extensions, e.g. ``x-badges``, ``x-code-samples``, etc.
:return:
"""
if methods is not None:
methods = [method.upper() for method in methods]
def decorator(f):
BaseSchema = (
# explicit manually set schema or previous view annotation
getattr(f, 'schema', None)
# previously set schema with @extend_schema on views methods
or getattr(f, 'kwargs', {}).get('schema', None)
# previously set schema with @extend_schema on @api_view
or getattr(getattr(f, 'cls', None), 'kwargs', {}).get('schema', None)
# the default
or api_settings.DEFAULT_SCHEMA_CLASS
)
if not inspect.isclass(BaseSchema):
BaseSchema = BaseSchema.__class__
def is_in_scope(ext_schema):
version, _ = ext_schema.view.determine_version(
ext_schema.view.request,
**ext_schema.view.kwargs
)
version_scope = versions is None or version in versions
method_scope = methods is None or ext_schema.method in methods
return method_scope and version_scope
class ExtendedSchema(BaseSchema):
def get_operation(self, path, path_regex, path_prefix, method, registry):
self.method = method.upper()
if exclude and is_in_scope(self):
return None
if operation is not None and is_in_scope(self):
return operation
return super().get_operation(path, path_regex, path_prefix, method, registry)
def get_operation_id(self):
if operation_id and is_in_scope(self):
return operation_id
return super().get_operation_id()
def get_override_parameters(self):
if parameters and is_in_scope(self):
return super().get_override_parameters() + parameters
return super().get_override_parameters()
def get_auth(self):
if auth and is_in_scope(self):
return auth
return super().get_auth()
def get_examples(self):
if examples and is_in_scope(self):
return super().get_examples() + examples
return super().get_examples()
def get_request_serializer(self):
if request is not empty and is_in_scope(self):
return request
return super().get_request_serializer()
def get_response_serializers(self):
if responses is not empty and is_in_scope(self):
return responses
return super().get_response_serializers()
def get_description(self):
if description and is_in_scope(self):
return description
return super().get_description()
def get_summary(self):
if summary and is_in_scope(self):
return str(summary)
return super().get_summary()
def is_deprecated(self):
if deprecated and is_in_scope(self):
return deprecated
return super().is_deprecated()
def get_tags(self):
if tags is not None and is_in_scope(self):
return tags
return super().get_tags()
def get_extensions(self):
if extensions and is_in_scope(self):
return extensions
return super().get_extensions()
if inspect.isclass(f):
# either direct decoration of views, or unpacked @api_view from OpenApiViewExtension
if operation_id is not None or operation is not None:
error(
f'using @extend_schema on viewset class {f.__name__} with parameters '
f'operation_id or operation will most likely result in a broken schema.'
)
# reorder schema class MRO so that view method annotation takes precedence
# over view class annotation. only relevant if there is a method annotation
for view_method_name in get_view_method_names(view=f, schema=BaseSchema):
if 'schema' not in getattr(getattr(f, view_method_name), 'kwargs', {}):
continue
view_method = isolate_view_method(f, view_method_name)
view_method.kwargs['schema'] = type(
'ExtendedMetaSchema', (view_method.kwargs['schema'], ExtendedSchema), {}
)
# persist schema on class to provide annotation to derived view methods.
# the second purpose is to serve as base for view multi-annotation
f.schema = ExtendedSchema()
return f
elif callable(f) and hasattr(f, 'cls'):
# 'cls' attr signals that as_view() was called, which only applies to @api_view.
# keep a "unused" schema reference at root level for multi annotation convenience.
setattr(f.cls, 'kwargs', {'schema': ExtendedSchema})
# set schema on method kwargs context to emulate regular view behaviour.
for method in f.cls.http_method_names:
setattr(getattr(f.cls, method), 'kwargs', {'schema': ExtendedSchema})
return f
elif callable(f):
# custom actions have kwargs in their context, others don't. create it so our create_view
# implementation can overwrite the default schema
if not hasattr(f, 'kwargs'):
f.kwargs = {}
# this simulates what @action is actually doing. somewhere along the line in this process
# the schema is picked up from kwargs and used. it's involved my dear friends.
# use class instead of instance due to descriptor weakref reverse collisions
f.kwargs['schema'] = ExtendedSchema
return f
else:
return f
return decorator
这个装饰器主要用于view
,通过drf-spectacular
部分或完全的覆盖去产生些东西
先来看下几个初始化参数
- operation_id:一个唯一标识ID,基本用不到
- parameters:添加到列表中的附加或替换参数去自动发现字段。
- responses:替换
Serializer
。需要各种各样的可单独使用或组合使用的输入(有以下7种)Serializer
类- 序列化实例,比如:
Serializer(many=True)
OpenApiTypes
的基本类型或者实例OpenApiResponse
类PolymorphicProxySerializer
类- 1个字典,以状态码作为键, 以上其中一项作为值(是最常用的,格式
{200, None}
) - 1个字典,以状态码作为键,以
media_type
作为值
- request:替换序列化,接受各种输入
Serializer
类或者实例OpenApiTypes
基本类型或者实例PolymorphicProxySerializer
类- 1个字典,以
media_type
作为键,以上其中一项作为值
- auth:用auth方法的显式列表替换发现的auth
- description:替换发现的文档字符串
- summary:一个可选的短的总结描述
- deprecated:将操作标记为已弃用
- tags:覆盖默认标记列表
- exclude:设置为True以从
schema
中排除操作 - operation:手动覆盖自动发现将生成的内容。你必须提供一个兼容
OpenAPI3
的字典,该字典可以直接翻译成YAML
。 - methods:检查
extend_schema
中特殊的方法,默认匹配所有 - versions:检查
extend_schema
中特殊的API版本,默认匹配所有 - example:将请求/响应示例附加到操作中
- extensions:规范扩展
Django(74)drf-spectacular自动生成接口文档的更多相关文章
- drf频率源码、自动生成接口文档、JWT
目录 一.drf频率源码分析 二.自动生成接口文档 1 安装依赖 2 设置接口文档访问路径 3 文档描述说明的定义位置 4 访问接口文档网页 三.JWT 1 JWT基本原理 1.1 header 1. ...
- day74:drf:drf其他功能:认证/权限/限流/过滤/排序/分页/异常处理&自动生成接口文档
目录 1.django-admin 2.认证:Authentication 3.权限:Permissions 4.限流:Throttling 5.过滤:Filtering 6.排序:OrderingF ...
- [Django REST framework - 自动生成接口文档、分页]
[Django REST framework - 自动生成接口文档.分页] 自动生成接口文档 # 后端人员写好接口,编写接口文档,给前端人员看,前端人员依照接口文档开发 # 公司里主流 -后端,使用w ...
- Django框架深入了解_05 (Django中的缓存、Django解决跨域流程(非简单请求,简单请求)、自动生成接口文档)
一.Django中的缓存: 前戏: 在动态网站中,用户所有的请求,服务器都会去数据库中进行相应的增,删,查,改,渲染模板,执行业务逻辑,最后生成用户看到的页面. 当一个网站的用户访问量很大的时候,每一 ...
- Django rest_framework 自动生成接口文档
自动生成接口文档 REST framework可以自动帮助我们生成接口文档. 接口文档以网页的方式呈现. 自动接口文档能生成的是继承自APIView及其子类的视图. 1. 安装依赖 REST fram ...
- django自动生成接口文档
我们在实际项目中,会需要将我们的一些接口的信息返回给前端,便于前后端的交互,在实际使用中,这种自动生成接口文档的模块很多,我主要是用REST framework自动生成接口文档,这个需要用到的是cor ...
- rbac介绍、自动生成接口文档、jwt介绍与快速签发认证、jwt定制返回格式
今日内容概要 RBAC 自动生成接口文档 jwt介绍与快速使用 jwt定制返回格式 jwt源码分析 内容详细 1.RBAC(重要) # RBAC 是基于角色的访问控制(Role-Based Acces ...
- drf07 过滤 排序 分页 异常处理 自动生成接口文档
4. 过滤Filtering 对于列表数据可能需要根据字段进行过滤,我们可以通过添加django-fitlter扩展来增强支持. pip install django-filter 在配置文件sett ...
- .net core 使用swagger自动生成接口文档
前言 swagger是一个api文档自动生动工具,还集成了在线调试. 可以为项目自动生成接口文档, 非常的方便快捷 Swashbuckle.AspNetCore 是一个开源项目,用于生成 ASP.N ...
随机推荐
- 利用 g4l 完整备份和还原Linux系统
前言: 1.Windows中Ghost由于一系列原因,有不支持分区格式,因此可能无法完整备份Linux. 2.g4l = Ghost for Linux 1.下载g4l https://sourcef ...
- jenkins的目录介绍
jenkins的目录介绍: /etc/init.d/jenkins #jenkins的启动文件 /etc/logrotate.d/jenkins /etc/sysconf ...
- 定要过python二级 第10套
第一部分 第一题 1. int* 字符串 =几个东西 2. 此题的最开始的疑惑 (1)01 02 03 怎么产生 for 循环 (2)<<< 这个怎么产生 (3)<这个&l ...
- 鸿蒙内核源码分析(编译过程篇) | 简单案例窥视GCC编译全过程 | 百篇博客分析OpenHarmony源码| v57.01
百篇博客系列篇.本篇为: v57.xx 鸿蒙内核源码分析(编译过程篇) | 简单案例窥视编译全过程 | 51.c.h.o 编译构建相关篇为: v50.xx 鸿蒙内核源码分析(编译环境篇) | 编译鸿蒙 ...
- Decorator装饰器模式个人理解
对于装饰器模式,其主要是为了:在不改变本体特征的情况下,对其进行包装.装饰,目的是为了补充.扩展.增强其功能. 有三个原则: 不能改变本体的特征 要对本体的功能进行扩展 装饰器脱离了本体则没有任何含义 ...
- 分布式、微服务必须配个日志管理系统才优秀,Exceptionless走起~~~
前言 在真实的项目中,不管是功能日志.错误日志还是异常日志,已经是项目的重要组成部分.在原始的单体架构,通常看日志的方式简单粗暴,直接登录到服务器,把日志文件拷贝下来进行分析:而如今分布式.微服务架构 ...
- excel模板数据填充 :tablefill
背景(问题) 在Web后台系统中或多或少都存在导入数据的功能,其中操作流程基本是 1.下载模板 2.填充模板数据 3.上传模板 但通常比较耗费时间的是填充模板数据这一步骤, 已自己为例之前的数据要么是 ...
- Incorrect datetime value: 时间添加失败原因
在进行单元测试中通过 new Date() 方式添加时间时,报了 Data truncation: Incorrect datetime value:这样的错误(我数据库表的时间类型是 datetim ...
- Serverless 工程实践 | Serverless 应用优化与调试秘诀
作者|刘宇 前言:本文将以阿里云函数计算为例,提供了在线调试.本地调试等多种应用优化与调试方案. Serverless 应用调试秘诀 在应用开发过程中,或者应用开发完成,所执行结果不符合预期时,我 ...
- C++核心编程 3 函数提高
函数默认参数 在C++中,函数的形参列表中的形参是可以有默认值的: 语法:返回值类型 函数名 (参数 = 默认值){ } 实例: #include<iostream> using name ...