serializers.SerializerMethodField response注释
@swagger_serializer_method(
serializer_or_field=SelfCarbonEmmissionSerializer)
def get_result_data(self, obj):
只需要写serializers对应返回数据结构即可
关于filter_fields注释
from django.utils.translation import gettext_lazy as _
class FilterDescriptionInspector(CoreAPICompatInspector):
def get_filter_parameters(self, filter_backend):
if isinstance(filter_backend, DjangoFilterBackend):
result = super(FilterDescriptionInspector, self).get_filter_parameters(filter_backend)
for param in result:
if not param.get('description', ''):
getattr_fields = getattr(self.view.serializer_class.Meta.model, param.name, '')
if type(getattr_fields) == bool:
if param.name == 'is_active':
param.description = '状态'
else:
param.description = '其他'
else:
if hasattr(getattr_fields.field, 'help_text'):
param.description = _(f"{(getattr(getattr_fields.field, 'help_text', ''))}")
else:
param.description = _(f"{(getattr(getattr_fields.field, 'verbose_name', ''))}")
return result
return NotHandled
@method_decorator(name='list', decorator=swagger_auto_schema(
filter_inspectors=[FilterDescriptionInspector]
))
适用与filter_fields
filter_fields = [‘audit_type’, ‘object_id’]
action :
@swagger_auto_schema(method='get', manual_parameters=[
openapi.Parameter(
name='gen_id',
in_=openapi.IN_QUERY,
description='机组编码',
required=True,
type=openapi.TYPE_STRING,
)
],
responses={200: MonthUnitProductPlanApiSerializer})
@action(detail=True, url_path="request_unit_plan_api",
methods=["get"])
- 自定義 GET 請求
如果希望自定義 GET 請求的參數呢?需要用 manual_parameters,比方說我希望依照 name 查詢 API,就可以這樣寫:
@swagger_auto_schema(
operation_summary='我是 GET 的摘要',
manual_parameters=[
openapi.Parameter(
name='name',
in_=openapi.IN_QUERY,
description='User Name',
type=openapi.TYPE_STRING
)
]
)
說明一下參數的意義:
name:參數名
in_:表示參數位於 request 的哪,比如:
openapi.IN_BODY,參數在 request 的 body,例如 POST 請求。
openapi.IN_QUERY,參數在 request 的 quey,例如 user/?name=123。
openapi.IN_FORM,參數在 request 的 form 表單,例如檔案上傳。
openapi.IN_PATH,參數在 request 的 path,比方說 /user/<id>/
type:參數的型別,如:openapi.TYPE_STRING、openapi.TYPE_NUMBER、openapi.TYPE_INTEGER、openapi.TYPE_BOOLEAN、openapi.TYPE_ARRAY、openapi.TYPE_FILE等,更多資訊可[參考官方文檔](https://drf-yasg.readthedocs.io/en/stable/drf_yasg.html#module-drf_yasg.openapi)。
- 自定義 Form 表單請求
Form 表單稍微複雜一點,需要指定 View 的 parser_class為 FormParser如果還有其他參數要一起提交,則要加上MultiPartParser不然會有以下錯誤:
Unsupported media type \”multipart/form-data; boundary= — — WebKitFormBoundaryU5zgTtpr7NV7zNFt\” in request.”
所以要改成:
from rest_framework.parsers import (
FormParser,
MultiPartParser
)
其他 packages 略 ...
class UsersView(GenericAPIView):
parser_classes = (FormParser, MultiPartParser)
@swagger_auto_schema(
operation_summary='我是 POST 的摘要',
operation_description='我是 POST 的說明',
manual_parameters=[
openapi.Parameter(
name='image',
in_=openapi.IN_FORM,
description='Image',
type=openapi.TYPE_FILE
),
]
)
def post(self, request, *args, **krgs):
略...
上传文件配置
# 不配置这个会报错,应该是已经创建表单了需要过滤掉上传文件的表单
parser_classes = (MultiPartParser,)
@swagger_auto_schema(operation_description='Upload File',
operation_id='Upload File',
manual_parameters=[openapi.Parameter(name='file',
in_=openapi.IN_FORM,
type=openapi.TYPE_FILE,
required=True,
description='Upload File'), ])