python - 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 中的字段屏蔽?
解决方案
推荐阅读
- android - invalidateOptionsMenu 未触发 onPrepareOptionsMenu()
- linux - 从文件中提取一个单词并将文件另存为该单词
- c# - 如何使用 c# 中的 pfx 文件中的证书对 JWT 令牌进行签名/取消签名?
- php - 插入到您有外键的表中并希望从另一个表中插入它
- android - 从可变列表中删除元素 - removeIf
- javascript - TypeScript 中的条件接口
- python - 在 Flask SQLAlchemy 中将数据插入到具有一对多关系的多个表中
- mysql - Varchar(65k) vs TEXT vs DB 订阅行
- python - 如何将注释放在列表行首?
- junit5 - junit 5 控制台启动器抛出错误“原因:java.lang.ClassNotFoundException”