Django:Swagger文档的配置
前言
第三方库drf-yasg
(Django Rest Swagger)。它是一个为Django Rest Framework提供Swagger/OpenAPI规范支持的库。按照以下步骤进行操作:
安装
pip install drf-yasg -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
配置
1、在项目的settings.py
INSTALLED_APPS = [ ... 'drf_yasg', ... ]
2、在项目的urls.py
低于Django 3.1版本
from django.conf.urls import url from django.urls import include from drf_yasg import openapi from drf_yasg.views import get_schema_view # 配置Swagger文档 schema_view = get_schema_view( openapi.Info( title="API文档", default_version='v1', description="API文档描述", terms_of_service="https://www.example.com/terms/", contact=openapi.Contact(email="contact@example.com"), license=openapi.License(name="BSD License"), ), public=True, ) # Swagger文档路由 urlpatterns = [ ... url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ... ]
Django 3.1版本及更高版本
from django.urls import re_path from django.urls import include from drf_yasg import openapi from drf_yasg.views import get_schema_view # 配置Swagger文档 schema_view = get_schema_view( openapi.Info( title="API文档", default_version='v1', description="API文档描述", terms_of_service="https://www.example.com/terms/", contact=openapi.Contact(email="contact@example.com"), license=openapi.License(name="BSD License"), ), public=True, ) # Swagger文档路由 urlpatterns = [ ... re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ... ]
启动项目并查看效果
访问http://localhost:8000/swagger/
,您将能够看到自动生成的Swagger文档
知道、想到、做到、得到
分类:
Django
, Django restframework
标签:
Django
, Django restframework
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2022-08-23 remote: The project you were looking for could not be found. 解决方案