
Pydantic的bool类型默认只能处理标准的Python布尔值(True/False)或可以直接转换为布尔值的类型(如整数0/1、空字符串/非空字符串等)。然而,在实际的API交互中,我们经常会遇到多种字符串表示形式来代表布尔状态,例如:
如果直接将Pydantic模型字段定义为bool类型,它将无法自动识别并转换这些自定义的字符串格式,导致验证失败或数据不准确。
from pydantic import BaseModel, Field
from typing import Optional
class MiscProblematic(BaseModel):
# 期望接收 "true" 或 "false",但直接定义为 bool 会失败
popup: Optional[bool] = None
# 期望接收 "yes" 或 "no",但直接定义为 bool 会失败
advertPending: Optional[bool] = None
# 尝试验证时会报错
# MiscProblematic(popup="true") # 这会引发 PydanticValidationErrorPydantic提供了一种强大的机制来处理这类自定义转换和验证需求:自定义验证器。通过使用pydantic.functional_validators.PlainValidator,我们可以定义一个函数,该函数接收原始输入值并返回转换后的值。
首先,我们定义一个核心的转换函数strToBool。这个函数负责接收一个字符串输入,将其规范化(去除首尾空白并转换为小写),然后根据预定义的“真值”和“假值”集合进行判断并返回相应的布尔值。
from typing import Annotated
from pydantic.functional_validators import PlainValidator
def strToBool(v: str) -> bool:
"""
将多种字符串表示形式转换为布尔值。
支持 "y", "yes", "on", "1", "enabled", "true" 转换为 True。
支持 "n", "no", "off", "0", "disabled", "false" 转换为 False。
对于无法识别的字符串,Pydantic会将其视为无效输入。
"""
if not isinstance(v, str):
# 如果输入不是字符串,Pydantic的PlainValidator通常会处理类型不匹配,
# 但这里可以明确指出,或者让Pydantic的默认行为处理。
# 对于此场景,我们主要关注字符串输入。
raise TypeError("Input must be a string for boolean conversion.")
normalized_v = v.strip().lower() # 规范化输入字符串
# 定义真值和假值的集合
truthy_values = {"y", "yes", "on", "1", "enabled", "true"}
falsy_values = {"n", "no", "off", "0", "disabled", "false"}
if normalized_v in truthy_values:
return True
elif normalized_v in falsy_values:
return False
else:
# 如果字符串不匹配任何已知的真值或假值,则视为无效输入
# Pydantic的PlainValidator期望在验证失败时抛出异常
raise ValueError(f"Invalid boolean string value: '{v}'. Expected one of {truthy_values.union(falsy_values)}")
# 使用 Annotated 和 PlainValidator 创建一个自定义布尔类型
extendedBool = Annotated[bool, PlainValidator(strToBool)]代码解析:
现在,我们可以将extendedBool这个自定义类型应用到我们的Pydantic模型中:
from pydantic import BaseModel, Field
from typing import Optional, Annotated
from pydantic.functional_validators import PlainValidator
# 假设 strToBool 函数和 extendedBool 类型已经定义如上
class Misc(BaseModel):
# - whether to pop-up checkbox ("true" or "false")
popup: extendedBool = False # 使用自定义的 extendedBool 类型
# - whether an advertisement is pending to be displayed ("yes" or "no")
advertPending: extendedBool = False # 使用自定义的 extendedBool 类型
# 示例用法
try:
# 成功转换的例子
data1 = Misc(popup="true", advertPending="yes")
print(f"Example 1: {data1.model_dump()}") # 输出: {'popup': True, 'advertPending': True}
data2 = Misc(popup="OFF", advertPending="1")
print(f"Example 2: {data2.model_dump()}") # 输出: {'popup': False, 'advertPending': True}
data3 = Misc(popup="0", advertPending="n")
print(f"Example 3: {data3.model_dump()}") # 输出: {'popup': False, 'advertPending': False}
# 包含 Optional 字段和默认值的例子
class Settings(BaseModel):
debug_mode: Optional[extendedBool] = None
feature_enabled: extendedBool = False
s1 = Settings(debug_mode="on")
print(f"Example 4: {s1.model_dump()}") # 输出: {'debug_mode': True, 'feature_enabled': False}
s2 = Settings(debug_mode=None, feature_enabled="TRUE")
print(f"Example 5: {s2.model_dump()}") # 输出: {'debug_mode': None, 'feature_enabled': True}
# 验证失败的例子
# s3 = Settings(debug_mode="invalid_value") # 这会引发 ValidationError
# print(f"Example 6: {s3.model_dump()}")
except Exception as e:
print(f"An error occurred: {e}")在这个Misc模型中,popup和advertPending字段现在被定义为extendedBool类型。当Pydantic接收到这些字段的字符串值时,它会自动调用strToBool函数进行转换。如果转换成功,字段将被赋值为相应的布尔值;如果转换失败(即strToBool抛出ValueError),Pydantic将捕获异常并报告验证错误。
将上述Pydantic模型集成到FastAPI中非常简单。FastAPI会自动利用Pydantic模型进行请求体、查询参数或路径参数的验证和转换。
from fastapi import FastAPI, Query
from typing import Optional
# 假设 Misc 模型和 extendedBool 类型已经定义如上
app = FastAPI()
@app.get("/api/misc_status/")
async def get_misc_status(
# FastAPI会自动使用 Misc 模型进行查询参数的解析和验证
params: Misc = Depends() # 或者直接在参数中定义 Misc 类型
):
"""
获取杂项状态,查询参数将自动转换为布尔值。
例如:/api/misc_status/?popup=true&advertPending=yes
"""
return {
"popup_status": params.popup,
"advert_pending_status": params.advertPending
}
# 另一种直接在 FastAPI 路由参数中使用 extendedBool 的方式
@app.get("/api/feature_toggle/")
async def get_feature_toggle(
feature_a_enabled: extendedBool = Query(False, description="是否启用特性A"),
feature_b_active: Optional[extendedBool] = Query(None, description="特性B是否激活")
):
"""
获取特性开关状态。
例如:/api/feature_toggle/?feature_a_enabled=on&feature_b_active=0
"""
return {
"feature_a_enabled": feature_a_enabled,
"feature_b_active": feature_b_active
}当客户端向/api/misc_status/发送请求时,例如GET /api/misc_status/?popup=true&advertPending=yes,FastAPI会将popup和advertPending的字符串值传递给Misc模型。Misc模型中的extendedBool类型会触发strToBool函数,最终将这些字符串转换为True。
通过Pydantic的PlainValidator自定义验证器,我们能够优雅且高效地解决FastAPI/Pydantic中多格式字符串到布尔值的转换问题。这种方法不仅提高了数据模型的灵活性和鲁棒性,还使得API能够更好地适应各种外部数据源的输入格式,是构建健壮Web服务的重要实践。通过清晰地定义转换逻辑和错误处理机制,我们可以确保应用程序在处理布尔类型数据时始终保持准确和可靠。
以上就是FastAPI/Pydantic 中灵活实现字符串到布尔值的转换的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号