簡體   English   中英

Pydantic - 在 response_model 中使用“Union”和“Field”時無法序列化/驗證

[英]Pydantic - Unable to serialize/validate while using “Union” with “Field” in response_model

  • 操作系統:Ubuntu 18.04.4 LTS
  • Python 版本:3.7.7
  • Pydantic 版本:1.4

我正在嘗試將class TableSetting作為BaseModel並將其作為response body 但似乎這個 class 中有一些驗證或序列化錯誤。 我想可能是UnionOptional[str]我使用但不確定。

源代碼

from fastapi import FastAPI, Query, Body, Path
from pydantic import BaseModel, Field
from typing import Union, Optional
from enum import Enum


app = FastAPI()


class Tableware(str, Enum):
    SPOON= "SPOON"
    FORK= "FORK"

class TableSetting(BaseModel):
    kitchen: Union[Tableware, Optional[str]] = Field(..., title="I am title")
    numberOfknife: int = Field(None, ge=0, le=4)

@app.post(
    "/{tableNumber}/provide-table-setting",
    response_model= TableSetting,    
)

def provide_table_setting(
    *,
    tableNumber: str= Path(...),
):
    results = {"tableNumber": tableNumber}
    return results

class TableSetting 的class TableSetting架構應如下所示

TableSetting{
    kitchen*        I am title{
                        anyOf ->    string  
                                    Enum:
                                        [ SPOON, FORK ]
                                    string
                    }
    numberOfknife   integer
                    maximum: 4
                    minimum: 0
}

在執行curl

curl -X POST "http://localhost:8000/2/provide-table-setting" -H  "accept: application/json"

它返回錯誤,響應代碼為 500, Internal Server Error ,似乎有些kitchen存在一些驗證問題,但我不知道為什么。

INFO:     127.0.0.1:53558 - "POST /2/provide-table-setting HTTP/1.1" 500 Internal Server Error
ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/home/*****/miniconda3/envs/fastAPI/lib/python3.7/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
.
.
.
  File "/home/*****/miniconda3/envs/fastAPI/lib/python3.7/site-packages/fastapi/routing.py", line 126, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for TableSetting
response -> kitchen
  field required (type=value_error.missing)

但是,當從代碼中刪除= Field(..., title="I a title")時,如下所示。 使用響應代碼 200可以正常工作,但是由於我需要Item kitchen根據需要,所以這不是我想要的。

class TableSetting(BaseModel):
    kitchen: Union[Tableware, Optional[str]]
    numberOfknife: int = Field(None, ge=0, le=4)

我怎樣才能解決這個問題?

謝謝

根據文檔聯盟,它接受不同的類型,但不是兩者都接受,而不是這個,你應該使用帶有 (required, optional) 之類的元組

from typing import Optional, Tuple
class TableSetting(BaseModel):
    kitchen: Tuple[Tableware, Optional[str]] = (None, Field(..., title="I am title"))
    #kitchen: Union[Tableware, Optional[str]] 
    numberOfknife: int = Field(None, ge=0, le=4)

暫無
暫無

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

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