首页 > 解决方案 > FastAPI 中的字段屏蔽(部分对象获取),如 Flask-Restx/Flask-RestPlus

问题描述

有没有办法像在 Flask-Restx/Flask-RestPlus 中一样在 FastAPI 中进行字段屏蔽(部分对象获取)?它不是内置的,我不确定最好的方法是什么。在 FastAPI 中,您可以在路由器方法中指定 response_model,但您似乎无法将该响应模型从输入更改为端点。

假设我们有

class ASchema(BaseModel):
    a: int = None
    b: str = None
    c: float = None
    d: bool = None


@router.get("/stuff", response_model=List[ASchema], response_model_exclude_unset=True)
def get_stuff(field_mask: str= None):
    return [ASchema(1, ‘string’, 1.1, true), ASchema(1, ‘strings’, 2.1, true), ASchema(1, ‘more strings’, 0, false)]

如果你只是在没有参数的情况下调用这个端点,你会得到

[{"a": 1, "b": "string", "c": 1.1, "d": true}, {"a": 1, "b": "strings", "c": 2.1, "d": true}, {"a": 1, "b": "more strings", "c": 0, "d": false}]

如果我提供了一个查询参数,field_mask = 'a,b'我想要这个响应:

[{"a": 1, "b": "string"}, {"a": 1, "b": "strings"}, {"a": 1, "b": "more strings"}]

目前,我一直在 FastAPI 中使用字段掩码,方法是使用 from_orm 将对象列表(如果它们不是 PyDantic 模式)转换为 Pydantic 模式,然后执行 copy(include=include_dict),其中 include_dict 是字典我想保留的字段。尽管这可行,但对于较大的列表来说似乎非常缓慢且效率低下,并且感觉太hacky而不是正确的。有没有更好的方法来完成 FastAPI 中的字段屏蔽?

标签: pythonfastapi

解决方案


推荐阅读