pip install drf-yasg2
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework','drf_yasg2', #自动生成接口文档'corsheaders', #cors浏览器跨域问题'erp_system', #系统管理模块,大模块下面有:用户管理、角色管理、功能菜单管理、权限管理、机构管理、日志管理
]
接口文档并不属于某一个接口的文档,是所有接口的文档,所以需要配置到项目的u全局urls中
from django.contrib import admin
from django.urls import path,re_path,include# drf_yasg 从这里开始
from rest_framework import permissions
from drf_yasg2.views import get_schema_view
from drf_yasg2 import openapi
from erp_system.views1 import Helloschema_view = get_schema_view(openapi.Info(title="API接口文档",default_version='V1',description="erp接口文档",),public=True,permission_classes=(permissions.AllowAny,), # 权限类
)urlpatterns = [path('admin/', admin.site.urls),re_path(r'^api/',include('erp_system.urls')), #路由以api开头re_path(r'^api/hello/',Hello.as_view()), #路由以api开头#path('docs/',include_docs_urls(title='接口测试平台API文档',description='这个是接口平台的文档')),re_path(r'^swagger(?P\.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'), # <-- 这里]
class MenuView(ModelViewSet):"""create:新增菜单参数:为Menu对象,其中delete_flag,create_time,update_time不用传参,return:添加之后的对象retrieve:查询单个菜单对象list:查询所有的菜单如果参数中有pid,则查询某一个父菜单下的所有子菜单列表,pid=0表示查询顶级菜单列表update:修改菜单destroy:删除某个菜单partial_update:局部修改菜单,修改任意的某个或者某几个属性"""queryset = MenuModel.objects.filter(delete_flag=0).all()serializer_class = MenuSerializer
以批量删除接口为例
swagger_auto_schema装饰器要定义在action装饰器的上面
from rest_framework.decorators import action
from drf_yasg2 import openapi
from drf_yasg2.utils import swagger_auto_schemadel_ids = openapi.Schema(type=openapi.TYPE_OBJECT, required=['ids'], properties={"ids": openapi.Schema(type=openapi.TYPE_ARRAY, items=openapi.Schema(type=openapi.TYPE_INTEGER),description="选择那些需要删除的ID(主键)")})
@swagger_auto_schema(method='delete', request_body=del_ids,operation_description="批量删除菜单") # 接口注释@action(methods=['delete'], detail=False)def multiple_delete(self, request, *args, **kwargs):delete_ids = request.data.get('ids') #json格式传递过来的if not delete_ids:return Response(data={'detail': '参数错误,ids为必填参数'}, status=status.HTTP_204_NO_CONTENT)elif not isinstance(delete_ids, list):return Response(data={'detail': '参数错误,ids必须为列表'}, status=status.HTTP_204_NO_CONTENT)# 先删除传递过来的菜单MenuModel.objects.filter(id__in=delete_ids).update(delete_flag='1')# 后删除所有的子菜单for m_id in delete_ids:MenuModel.objects.filter(parent_id=m_id).update(delete_flag='1')return Response(status=status.HTTP_204_NO_CONTENT)
访问http://127.0.0.1:8000/swagger/,访问接口文档页面展示
下一篇:Problem Set 3