django 定义自定义请求- Swagger(Drf-yasg)

oxf4rvwz  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(218)

我有一个用例,其中请求的必填字段根据请求的字段值之一而有所不同。
例如,如果请求中可移动类型的值是'P',则某些字段是强制的,否则,如果移动类型的值是'D',则某些其它字段是强制的。
如何使用drf-yasg为这样的用例创建自定义请求?

k0pti3hp

k0pti3hp1#

根据我在drf_yasg docs中发现的内容,您需要实现一个名为 * Inspector classes* 的概念来自定义与特定字段、序列化程序、过滤器或分页器类相关的行为,您可以实现FieldInspectorSerializerInspectorFilterInspectorPaginatorInspector类,并将它们与@swagger_auto_schemarelated settings之一一起使用。
下面是一个FieldInspector示例,它从所有生成的Schema对象中删除title属性,并取自**Inspector类**[drf_yasg-docs]:

from drf_yasg.inspectors import FieldInspector

class NoSchemaTitleInspector(FieldInspector):
  def process_result(self, result, method_name, obj, **kwargs):
     # remove the `title` attribute of all Schema objects
     if isinstance(result, openapi.Schema.OR_REF):
        # traverse any references and alter the Schema object in place
        schema = openapi.resolve_ref(result, self.components)
        schema.pop('title', None)

        # no ``return schema`` here, because it would mean we always generate
        # an inline `object` instead of a definition reference

     # return back the same object that we got - i.e. a reference if we got >a reference
     return result

class NoTitleAutoSchema(SwaggerAutoSchema):
  field_inspectors = [NoSchemaTitleInspector] + >swagger_settings.DEFAULT_FIELD_INSPECTORS

class ArticleViewSet(viewsets.ModelViewSet):
  swagger_schema = NoTitleAutoSchema
  ...

相关问题