drf_yasg2 自定义swagger接口参数,不需要定义model和serializer

from django.utils.decorators import method_decorator
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi


class BatchTestSuiteView(CustomViewSet): """ custom batch delete or single delete with suite_ids :doc 一个用户自定义swagger参数的接口演示,不需要定义模型model和序列化器serializer penapi.TYPE Includes: TYPE_OBJECT = "object" #: TYPE_STRING = "string" #: TYPE_NUMBER = "number" #: TYPE_INTEGER = "integer" #: TYPE_BOOLEAN = "boolean" #: TYPE_ARRAY = "array" #: TYPE_FILE = "file" #: in_ includes: IN_BODY = 'body' #: IN_PATH = 'path' #: IN_QUERY = 'query' #: IN_FORM = 'formData' #: IN_HEADER = 'header' #: with swagger_auto_schema: :param str name: parameter name :param str in_: parameter location :param str description: parameter description :param bool required: whether the parameter is required for the operation :param schema: required if `in_` is ``body`` :type schema: Schema or SchemaRef :param str type: parameter type; required if `in_` is not ``body``; must not be ``object`` :param str format: value format, see OpenAPI spec :param list enum: restrict possible values :param str pattern: pattern if type is ``string`` :param .Items items: only valid if `type` is ``array`` :param default: default value if the parameter is not provided; must conform to parameter type """ lookup_field = 'id' parser_classes = [JSONParser, FormParser] serializer_class = SerialTestSuite queryset = TestSuite.objects.all() query_param = openapi.Parameter(name='suite_ids', in_=openapi.IN_QUERY, description="套件id", type=openapi.TYPE_STRING) @swagger_auto_schema(method='delete', manual_parameters=[query_param]) @action(methods=['delete'], detail=False, ) def batch_delete(self, request, *args, **kwargs): suite_ids_string = request.query_params.get('suite_ids', None) suite_ids = suite_ids_string.split(',') if not suite_ids: return CustomResponse(data=[], msg="请选择suite_id,suite_id不能为空" , success=False, code=400) self.get_queryset().filter(id__in=suite_ids).delete() return CustomResponse(data=[], msg='删除成功!', code=200, success=True)



效果:

 

 

 

 

 

路由:

path('testsuite/batch',views.BatchTestSuiteView.as_view({'delete':'batch_delete'}))


注意这里 CustomViewSet是自己写的一个继承:
from rest_framework.viewsets import ModelViewSet, GenericViewSet, ViewSet
from .custom_response import CustomResponse


class CustomViewSet(ModelViewSet):
""" ViewSetMixin resolve url path tip always """
def create(self, request, *args, **kwargs):
response = super().create(request, *args, **kwargs)
return CustomResponse(data=response.data, code=200,
msg='ok', success=True)

def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)

return CustomResponse(data=response.data, code=200,
msg='ok', success=True)

def update(self, request, *args, **kwargs):
response = super().update(request, *args, **kwargs)
return CustomResponse(data=response.data, code=200,
msg='ok', success=True)

def retrieve(self, request, *args, **kwargs):
response = super().retrieve(request, *args, **kwargs)
return CustomResponse(data=response.data, code=200,
msg='ok', success=True)

def destroy(self, request, *args, **kwargs):
response=super().destroy(request, *args, **kwargs)

return CustomResponse(data=response.data, code=200,
msg='ok', success=True)
 
# post body 包含数组案例:
class BatchTestCaseView(CustomViewSet):
lookup_field = 'id'
queryset = TestCase.objects.all()
serializer_class = SerializerTestCase
parser_classes = [JSONParser, FormParser]

query_param = openapi.Parameter(name='case_ids', in_=openapi.IN_QUERY, description="用例id",
type=openapi.TYPE_STRING)


@swagger_auto_schema(method='delete', manual_parameters=[query_param])
@action(methods=['delete'], detail=False)
def batch_delete(self, request, *args, **kwargs):
pass

@swagger_auto_schema(method='post',
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['suite_ids'],

properties={'suite_ids': openapi.Schema(type=openapi.TYPE_ARRAY,
items=openapi.Schema(type=openapi.TYPE_INTEGER))}
),
operation_description='suite_ids'

)
@action(methods=['post'], detail=False)
def batch_run(self, request, *args, **kwargs):
pass
 
post body json 案例:
class UserInfo(CustomViewSet):
parser_classes = [JSONParser, FormParser]
serializer_class = UserSerializer
queryset = User.objects.all()

@swagger_auto_schema(method='patch',
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['new_password','username','password'],

properties=
{
'username':openapi.Schema(type=openapi.TYPE_STRING,description='用户名'),
'password':openapi.Schema(type=openapi.TYPE_STRING,description='旧密码'),
'new_password': openapi.Schema(type=openapi.TYPE_STRING,description='新密码')
}
),
operation_description='修改用户信息'

)
@action(methods=['patch'], detail=False)
def change_password(self, request, *args, **kwargs):
pass
return CustomResponse(data=[], code=200,
msg='修改信息成功!', success=True)

 

 

 
posted @ 2021-01-25 11:41  不带R的墨菲特  阅读(3417)  评论(4编辑  收藏  举报