我正在构建一个FastAPI应用程序,其中包含许多Pydantic模型。尽管该应用程序正常运行,但如预期的那样,OpenAPI(Swagger UI)文档在部分中并未显示所有这些模型的模式。
以下是pydantic schemas.py
的内容:
import socket
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Union
from pydantic import BaseModel, Field, validator
from typing_extensions import Literal
ResponseData = Union[List[Any], Dict[str, Any], BaseModel]
# Not visible in Swagger UI
class PageIn(BaseModel):
page_size: int = Field(default=100, gt=0)
num_pages: int = Field(default=1, gt=0, exclude=True)
start_page: int = Field(default=1, gt=0, exclude=True)
# visible under schemas on Swagger UI
class PageOut(PageIn):
total_records: int = 0
total_pages: int = 0
current_page: int = 1
class Config: # pragma: no cover
@staticmethod
def schema_extra(schema, model) -> None:
schema.get("properties").pop("num_pages")
schema.get("properties").pop("start_page")
# Not visible in Swagger UI
class BaseResponse(BaseModel):
host_: str = Field(default_factory=socket.gethostname)
message: Optional[str]
# Not visible in Swagger UI
class APIResponse(BaseResponse):
count: int = 0
location: Optional[str]
page: Optional[PageOut]
data: ResponseData
# Not visible in Swagger UI
class ErrorResponse(BaseResponse):
error: str
# visible under schemas on Swagger UI
class BaseFaultMap(BaseModel):
detection_system: Optional[str] = Field("", example="obhc")
fault_type: Optional[str] = Field("", example="disk")
team: Optional[str] = Field("", example="dctechs")
description: Optional[str] = Field(
"",
example="Hardware raid controller disk failure found. "
"Operation can continue normally,"
"but risk of data loss exist",
)
# Not visible in Swagger UI
class FaultQueryParams(BaseModel):
f_id: Optional[int] = Field(None, description="id for the host", example=12345, title="Fault ID")
hostname: Optional[str]
status: Literal["open", "closed", "all"] = Field("open")
created_by: Optional[str]
environment: Optional[str]
team: Optional[str]
fault_type: Optional[str]
detection_system: Optional[str]
inops_filters: Optional[str] = Field(None)
date_filter: Optional[str] = Field("",)
sort_by: Optional[str] = Field("created",)
sort_order: Literal["asc", "desc"] = Field("desc")
所有这些模型都实际用于FastAPI路径(path)以验证请求体(request body)。
FaultQueryParams
是自定义模型,我用它来验证请求查询参数(query params),并像下面这样使用它:
query_args: FaultQueryParams = Depends()
其余的模型与 Body
字段一起使用。 我无法弄清楚为什么只有其中一些模型不显示在 Schemas
部分中而其他模型则显示出来。另外,我注意到关于
FaultQueryParams
的另一件事是,即使它们在模型中定义了,描述和示例也不会显示在路径终点(endpoint)上。编辑1:
我进一步研究并意识到,所有在Swagger UI中不可见的模型都是那些没有直接用作路径操作的模型,即这些模型不被用作
response_model
或 Body
类型,并且是间接使用的辅助模型。因此,似乎FastAPI没有为这些模型生成架构(schema)。以上声明的一个例外是
query_args: FaultQueryParams = Depends()
,它被直接用于路径操作以将终点(endpoint)的查询(Query)参数映射到自定义模型。 这是一个问题,因为swagger没有识别此模型的字段中的元参数(如 title
, description
, example
),并且未显示在UI中,这对于该终点(endpoint)的用户非常重要。是否有一种方法可以欺骗FastAPI生成自定义模型
FaultQueryParams
的架构(schema),就像它为 Body
,Query
等生成架构(schema)?