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

FastAPI使用regex路径约束时提示字段regex规则未被执行报错如何解决

报错诱因

你给int类型的路径参数加了regex约束,而Pydantic的正则校验规则仅针对字符串类型生效,不会对数值类型执行正则匹配,因此会抛出约束未生效的报错。FastAPI的参数校验逻辑完全依赖Pydantic实现,不存在底层自动处理非规则约束的逻辑。

解决方法

根据你的业务场景可以选择以下两种方案:

  • 方案一:将参数类型改为str(更推荐,序列号类字段通常用字符串存储可避免数值溢出、前导零丢失等问题),修改后regex约束会自动生效:
@devices.get("/{serial}", response_model=Device)
async def get_serial(serial: str = Path(..., regex=r"(?:\d{18}|\d{24})")) -> dict:
    # 你的业务逻辑
  • 方案二:如果必须保留int类型,替换正则约束为数值范围校验,或者自定义校验器:
    1. 用数值范围校验(仅校验位数区间,无法严格限制只能是18或24位):
    @devices.get("/{serial}", response_model=Device)
    async def get_serial(serial: int = Path(..., ge=10**17, le=10**24 - 1)) -> dict:
    
    1. 用自定义校验器严格限制只能是18或24位:
    from typing import Annotated
    from pydantic import AfterValidator
    
    def validate_serial_digits(v: int) -> int:
        digit_length = len(str(v))
        if digit_length not in (18, 24):
            raise ValueError("serial must be 18 or 24 digits")
        return v
    
    @devices.get("/{serial}", response_model=Device)
    async def get_serial(serial: Annotated[int, Path(...), AfterValidator(validate_serial_digits)]) -> dict:
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:45:08