簡體   English   中英

定義自定義請求 - Swagger (Drf-yasg)

[英]Defining custom request - Swagger (Drf-yasg)

我有一個用例,其中請求所需的字段根據請求的字段值之一而不同。

例如,如果請求中的可移動類型的值為'P' ,則某些字段是必填的,否則,如果移動類型的值為'D' ,則其他一些字段是必填的。

如何使用drf-yasg為此類用例創建自定義請求?

根據我在drf_yasg 文檔中發現的內容,您需要實現一個名為Inspector的概念來自定義與特定字段、序列化器、過濾器或分頁器類相關的行為,您可以實現FieldInspectorSerializerInspectorFilterInspectorPaginatorInspector類並將它們與@swagger_auto_schema一起使用@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 - ie 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...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM