网上很多资料在介绍Django
接入Swagger
方法时,都是基于django-rest-swagger
库进行讲解的,都殊不知,从2019年6月份开始,官方已经废弃了该库,在django 3.0中已经不支持该库了,取而代之的是全新的第三方drf-yasg
库。
1.安装库
pip3 install drf-yasg
2.注册应用
settings.py
文件中进行注册第三方应用
INSTALLED_APPS = [
# 注册第三方子应用
'polls.apps.PollsConfig', # 大部分情况简写成'polls'
'rest_framework',
'django_filters',
#swagger接口文档
'drf-yasg',
#自己创建的应用
'projects.apps.ProjectsConfig',
'interfaces.apps.InterfacesConfig',
]
3.添加路径
urls.py
文件中添加路径
from django.contrib import admin
from django.urls import path, include, re_path
#2. coreapi文档需要进行的导入信息
from rest_framework.documentation import include_docs_urls
#swagger接口文档
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="接口平台API",
default_version='v1.0',
description="接口平台接口文档",
terms_of_service="#",
contact=openapi.Contact(email="测试"),
license=openapi.License(name="BSD License"),
),
public=True,
)
urlpatterns = [
# path('/', include('projects.urls')),
path('admin/', admin.site.urls), # 进入localhost:8000/admin会进入Django的admin管理页面
path('polls/', include('polls.urls')),
path('', include('projects.urls')),
path('interfaces/', include('interfaces.urls')),
#3. coreapi文档路径
path('docs/',include_docs_urls(title="接口测试平台API文档",
description="这个是接口平台的文档"
)),
# 配置drf-yasg路由
re_path('^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
path('swagger', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
4.运行: