安装和配置
1.安装
pip install drf-yasg
2.settings.py 文件中注册第三方应用
INSTALLED_APPS = [
*****
"django.contrib.staticfiles", # swagger用到的静态资源在这里
# swagger接口文档
'drf_yasg',
*****
]
3.urls.py中添加路径
#swagger接口文档
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from django.urls import path,include,re_path
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,
# permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
*****
# 配置drf-yasg路由
# 访问路径 /swagger.json 好像没啥用
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.使用
给接口加注释
视图集(list,create,update,destrory, retrieve) 和 视图类的加法如下
from django.utils.decorators import method_decorator
from drf_yasg.utils import swagger_auto_schema
@method_decorator(name='get',decorator=swagger_auto_schema(operation_summary="获取项目列表"))
@method_decorator(name='post',decorator=swagger_auto_schema(operation_summary="新增项目"))
class InterfacesView(APIView):
....
效果
给函数视图的加法是这么加的