仅允许 Pydantic 模型的某些字段传递到 FastAPI 端点

问题描述 投票:0回答:1

假设我有一个经过验证的 Pydantic 模型:

Name = Annotated[str, AfterValidator(validate_name)]

class Foo(BaseModel):
    id: UUID = Field(default_factory=uuid4)
    name: Name

还有一个 FastAPI 端点:

@app.post('/foos')
def create_foo(foo: Foo) -> Foo:
    save_to_database(foo)
    return foo

我只希望调用者能够传递

name
的值,但不能传递
id
的值。有没有办法做这样的事情?

def create_foo(foo: Annotated[Foo, Body(include=['id'])]) -> Foo:

我知道我能做到:

@app.post('/foos')
def create_foo(name: Annotated[str, Body(embed=True)]) -> Foo:
    foo = Foo(name=name)
    save_to_database(foo)
    return foo

但是隐式验证错误处理不再起作用,我需要添加更多代码来做到这一点。

有什么优雅的处理方式吗?

python fastapi pydantic
1个回答
0
投票
字段的

排除选项可能会帮助您。

class Foo(BaseModel):
    id: UUID = Field(default_factory=uuid4, exclude=True)
    name: Name
© www.soinside.com 2019 - 2024. All rights reserved.