如何使用 pydantic/fastapi 在单个路线上接受具有 array\single 项的对象?

How do I accept on a single route objects with array\single items using pydantic/fastapi?

假设我有:

from pydantic import BaseModel
from typing import Optional, List

class Create(BaseModel):
    code: List[str] = []
    args: List[str] = []

包装成类似

的东西
@router.post('/new', status_code=201)
async def create_project(data: Create):
    pass

所以 code and/or args 是请求者的数组或单个值?

这样,对单个路由的请求可能包含以下任何内容:

{code: "code", args: "arg"}
{code: ["code"], args: "arg"}
{code: ["code"], args: ["arg"]}
{code: "code", args: ["arg"]}

并且始终使用使用列表的真实类型调用处理程序?

您有很多可能性,其中一种通用的方法是使用 validator(或根验证器),并在其中将单个值解析为列表。像这样:

class Create(BaseModel):
    code: List[str] = []

    @validator('code', pre=True)
    def code_validate(cls, values):
        if not isinstance(values, list):
            values = [values]
        return values

Pydantic 模型接受 Union 作为字段定义,例如:

from typing import List, Union

class Create(BaseModel):
    code: Union[str, List[str]] = []
    args: Union[str, List[str]] = []

在这种情况下,codeargs 都将接受 str 或 list/array 的 str

codeargs 都将默认为空 list

其余代码保持不变,例如:

from fastapi import FastAPI, status

app = FastAPI()

@app.post("/create", status_code=status.HTTP_201_CREATED)
async def create_project(data: Create):
    return data

用单个项目调用端点:

$ curl -i -X 'POST' 'http://127.0.0.1:8000/create' \
    -H 'accept: application/json' \
    -H 'Content-Type: application/json' \
    -d '{"code": "code", "args": "arg"}'

HTTP/1.1 201 Created
date: Sun, 29 Aug 2021 10:25:57 GMT
server: uvicorn
content-length: 28
content-type: application/json

{"code":"code","args":"arg"}

调用具有多个项目的端点:

$ curl -i -X 'POST' 'http://127.0.0.1:8000/create' \
    -H 'accept: application/json' \
    -H 'Content-Type: application/json' \
    -d '{"code": ["code"], "args": ["arg"]}'

HTTP/1.1 201 Created
date: Sun, 29 Aug 2021 10:27:03 GMT
server: uvicorn
content-length: 32
content-type: application/json

{"code":["code"],"args":["arg"]}