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

我正在尝试制作class TableSettingasBaseModel并将其作为response body. 但似乎这个类中有一些验证或序列化错误。我想这可能是Union或者Optional[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

的 json 模式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)

我怎样才能解决这个问题?

谢谢

4

1 回答 1

2

根据文档联盟,它接受不同的类型,但不是两者都接受,而不是这个,你应该使用带有 (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)
于 2020-04-22T07:14:03.653 回答