python - 使用带有 FastApi (Pydantic) 的 List[Union[...]] 时评估模型列表中的可选字段
问题描述
给定一个带有多个响应模型的 FastAPI 端点,我希望能够根据它们的可选字段(而不是默认的必填字段)评估所有所述模型。
示例代码:
class A:
required_field
optional_field_A
class B:
required_field
optional_field_B
response_model = List[Union[A, B]]
# Given the following sample response data
raw_response_data = [
{'required_field': 'foo_A', 'optional_field_A': 'bar_A'},
{'required_field': 'foo_B', 'optional_field_B': 'bar_B'}
]
# Based on `response_model`, raw data will be translated to the following:
translated_data = [
{'required_field': 'foo_A', 'optional_field_A': 'bar_A'},
{'required_field': 'foo_B'}
]
如上所示,响应模型将仅根据必填字段评估我的模型的联合。
一个快速的肮脏技巧:
我能够通过将两个模型组合在一个 OOP 继承的联合中来解决:
class AB(A, B):
"""A synthetic union between A and B"""
pass
# This solves my output schema
response_model = List[AB]
我对这个解决方案的问题是它有点误导,因为 API 客户端不能确定验证他们的数据来自哪个模型。(是A?还是B?)
所需的解决方案:
我想在 Pydantic 中有一个选项可以禁止在模型上设置“错误字段”,而不会破坏联合操作。换句话说,评估模型A
,如果传递了错误的字段,则评估模型B
。如果没有找到匹配项,则抛出错误。
解决方案
推荐阅读
- python - IndexError on 3-dimensional arrays
- javascript - How to convert cURL to axios
- node.js - Why does my function return "undefined" but works with console.log please ? How to solve that please?
- python - 无界二分搜索(找到单调递增函数变为零的点)
- php - 只获取号码,不带任何文字
- logging - pytset - 如何配置显示日志消息
- tinymce - 我需要创建将在按下按钮时隐藏和显示的文本和图像元素
- javascript - 在 iframe 中显示和下载 pdf
- html - 点击(不是
) 关闭“披露声明”?
- python - 带有自定义 ldap 过滤器的 ldap3 阅读器