是否可以使用 fastapi 为请求主体的列表属性强加长度?

Is it possible to impose the length for a list attribute of the request body with fastapi?

是否可以在请求正文(或响应)的模式中指定列表的长度?支持使用 Query 函数验证在 url 中传递的字符串的长度,但我看不到列表的任何内容。 可能的用例是发送固定大小的浮点列表以提供给 ML 模型。

您可以 use the Field functionmin_itemsmax_items:

from pydantic import Field

class Foo(BaseModel):
    fixed_size_list_parameter: float = Field(..., min_items=4, max_items=4)

.. 或者你可以 use the conlist (constrained list) type 来自 pydantic:

from pydantic import conlist

class Foo(BaseModel):
    fixed_size_list_parameter: conlist(float, min_items=4, max_items=4)

这将列表限制为 float 类型的四个条目。