django项目中使用swagger来实现接口文档自动生成
2024-10-20 06:38:27
一、Swagger
一般我们在对接前后端的时候,都需要提供相应的接口文档。对于后端来说,编写接口文档即费时费力,还会经常因为没有及时更新,导致前端对接时出现实际接口与文档不一致。而且手写接口文档还容易出错,而swagger很好的解决了这个痛点。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。可用于:1.接口的文档在线自动生成、2.功能测试。
二、在DjangorestFramework中自动生成接口文档drf_yasg
REST framework可以自动帮助我们生成接口文档。
接口文档以网页的方式呈现。
自动接口文档能生成的是继承自APIView
及其子类的视图。
# 安装
pip install drf_yasg # 添加
INSTALLED_APPS = [
'drf_yasg',
'rest_framework'
,
]
# urls.py from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="接口文档平台", # 必传
default_version='v1', # 必传
description="文档描述",
terms_of_service='',
contact=openapi.Contact(email="###@qq.com"),
license=openapi.License(name="BSD LICENSE")
),
public=True,
# permission_classes=(permissions.) # 权限类
# permission_classes=(permissions.AllowAny,) # 可以允许任何人查看该接口
# permission_classes=(permissions.IsAuthenticated) # 只允许通过认证的查看该接口
)
urlpatterns += [
# re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0)),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
# settings.py
# Swagger配置 https://github.com/axnsan12/drf-yasg/issues/58
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False,
'SECURITY_DEFINITIONS': {
'api_key': {
'type': 'apiKey',
'in': 'header',
'name': 'Authorization'
}
},
}
drf_yasg官网:https://drf-yasg.readthedocs.io/
drf_yasg:https://github.com/axnsan12/drf-yasg
最新文章
- SQL多表查询,消除表中的重复的内容
- 借助 Lucene.Net 构建站内搜索引擎(上)
- sql server 基础语句
- AC日记——加密的病历单 openjudge 1.7 12
- Webclent基本操作
- AndroidStudio-OSX 常用快捷键整理
- erl0004 - ets 安全遍历
- Mem Cgroup目录无法清理问题分析
- webbench的详细使用
- resin4 简单学习
- CGContext
- centos/linux下的安装Maven
- 移动端控制视频点击播放点击下一个视频时自动停止播放&;监听滑动溢出屏幕高度时停止播放
- MySQL自动备份shell脚本
- Fiddler抓包【6】_Fiddler Script
- 在Eclipse中Tomcat配置图片保存路径
- 用Java执行Python:Jython踩坑笔记
- SpringSecurity-ExceptionTranslationFilter的作用
- djiango web 在进入admin的时候出现&#39;set&#39; object is not reversible错误
- 使用BigDecimal转换较长小数时候出现科学计数法的问题