개발하자
빠른 사용API 및 Pydantic, 설명과 함께 옵션 필드를 정의하려면 어떻게 해야 합니까?
Cuire
2022. 11. 9. 20:13
반응형
빠른 사용API 및 Pydantic, 설명과 함께 옵션 필드를 정의하려면 어떻게 해야 합니까?
단식을 위해API Pydannoctic 클래스 나는 이 값들을 가지고 있다.
class ErrorReportRequest(BaseModel):
sender: Optional[str] = Field(..., description="Who sends the error message.")
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
클래스를 입력 모델로 사용합니다.
router = APIRouter()
@router.post(
"/error_report",
response_model=None,
include_in_schema=True,
)
def error_report(err: ErrorReportRequest):
pass
이 필드를 실행할 때는 필수 필드입니다. 만약 그것이 들어오는 JSON에 포함되지 않는다면, 나는 유효성 검사 오류를 받는다.
입력:
{
"error_message_displayed_to_client": "string"
}
결과:
{
"detail": [
{
"loc": [
"body",
"sender"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
다음과 같이 필드 설명을 제거하는 경우:
class ErrorReportRequest(BaseModel):
sender: Optional[str]
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
요청이 통과되다.
필드 이름을 생략할 수 있도록 옵션 필드에 필드 설명을 추가하려면 어떻게 해야 합니까?
예를 들어 다음과 같이 명시적 기본값을 에 제공해야 합니다.
class ErrorReportRequest(BaseModel):
sender: Optional[str] = Field(None, description="Who sends the error message.")
error_message_displayed_to_client: str = Field(..., description="The error message displayed to the client.")
값이 필수임을 나타냅니다. 이것은 물론 와 충돌하지만, 파이든틱은 에 더 높은 우선 순위를 부여하는 것처럼 보인다.
에서:
: (위치 인수) 필드의 기본값입니다. 이 필드의 기본값을 대체하므로 이 첫 번째 인수를 사용하여 기본값을 설정할 수 있습니다. 생략 부호()를 사용하여 필드가 필요함을 나타냅니다.
반응형