You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI+Pydantic使用PurePath时JSON Schema无法声明类型报错如何解决

问题原因

你配置的json_encoders仅负责Pydantic模型序列化为JSON时的转换逻辑,而生成OpenAPI Schema时,Pydantic无法识别PureWindowsPath这类非内置标准类型的JSON Schema定义,因此抛出Value not declarable with JSON Schema错误。

修复方案

方案1:快速适配(适合单字段使用)

步骤1:在基类模型的Config配置中开启任意类型允许

给你的CamelModel的Config类添加arbitrary_types_allowed = True配置,允许Pydantic处理非内置标准类型。

步骤2:给PureWindowsPath字段显式指定Schema

通过Field参数显式声明该字段在OpenAPI中的类型为字符串。
修改后的完整代码示例:

from pydantic import BaseModel, Field
from abc import ABC
from pathlib import PureWindowsPath, PurePath
from datetime import datetime
# 你的camelize导入保持不变

class CamelModel(BaseModel, ABC):
    class Config:
        alias_generator = camelize
        allow_population_by_field_name = True
        frozen = True
        arbitrary_types_allowed = True # 新增配置
        json_encoders = {
            datetime: lambda dt: dt.isoformat(),
            PureWindowsPath: str,
            PurePath: str
        }
        use_enum_values = True

class Foo(CamelModel, ABC):
    # 新增Field配置指定Schema
    path: PureWindowsPath = Field(..., description="Windows文件路径", example="C:\\Users\\xxx\\test.txt", type="string")
    extraction_version: str

class Foo2(Foo):
    pass

方案2:自定义可复用的路径类型(适合多场景复用)

你可以封装一个自带Schema声明的自定义PureWindowsPath类型,后续所有用到该类型的字段无需额外配置:

from pydantic import BaseModel, GetCoreSchemaHandler
from pydantic_core import core_schema
from pathlib import PureWindowsPath
from abc import ABC

# 自定义Pydantic兼容的PureWindowsPath类型(Pydantic V2写法)
class PydanticPureWindowsPath(PureWindowsPath):
    @classmethod
    def __get_pydantic_core_schema__(cls, source_type, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema:
        return core_schema.no_info_wrap_validator_function(
            cls,
            core_schema.str_schema(),
            serialization=core_schema.plain_serializer_function_ser_schema(str, return_schema=core_schema.str_schema())
        )

# 如果你使用的是Pydantic V1,用以下写法:
# class PydanticPureWindowsPath(PureWindowsPath):
#     @classmethod
#     def __modify_schema__(cls, field_schema):
#         field_schema.update(
#             type="string",
#             format="windows-path",
#             examples=["C:\\Users\\xxx\\test.txt"],
#         )
#
#     @classmethod
#     def __get_validators__(cls):
#         yield cls.validate
#
#     @classmethod
#     def validate(cls, v):
#         return PureWindowsPath(v)

# 业务模型直接使用自定义类型即可
class Foo(CamelModel, ABC):
    path: PydanticPureWindowsPath
    extraction_version: str

修改完成后重启服务即可正常访问SwaggerUI,OpenAPI会自动将路径字段识别为字符串类型,同时保留输入输出时的自动类型转换能力。

内容的提问来源于stack exchange,提问作者Teharez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 22:42:01