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

如何在FastAPI的BaseModel外替代已弃用的Pydantic constr?

替代Pydantic已弃用constr的现代方案(FastAPI路由参数校验)

Pydantic v2 已弃用constr,推荐使用Annotated结合Pydantic的校验组件来实现路由参数的字符串约束,完全替代原有constr的strict、to_upper、max_length等功能,且符合当前最佳实践。

方案1:使用StringConstraints

通过StringConstraints明确定义字符串的校验规则,配合StrictStr实现strict=True的效果:

from pydantic import StringConstraints, StrictStr
from fastapi import FastAPI
from typing import Annotated

# 对应原constr(strict=True, to_upper=True, max_length=4)
SiteCode = Annotated[
    StrictStr,
    StringConstraints(max_length=4, to_upper=True)
]

app = FastAPI()

@app.get("/{site_code}", summary="Read a site")
async def get_site(site_code: SiteCode) -> str:
    return f"Validated site code: {site_code}"

方案2:使用Field

直接在Annotated中通过Field指定校验参数,效果与方案1一致:

from pydantic import Field, StrictStr
from fastapi import FastAPI
from typing import Annotated

SiteCode = Annotated[
    StrictStr,
    Field(max_length=4, to_upper=True)
]

app = FastAPI()

@app.get("/{site_code}", summary="Read a site")
async def get_site(site_code: SiteCode) -> str:
    return f"Validated site code: {site_code}"

说明

  • StrictStr强制要求输入为严格字符串类型,对应原constr的strict=True;
  • to_upper=True会自动将输入字符串转为大写,不符合长度限制的请求会被FastAPI自动拦截并返回422错误;
  • 两种方案均支持在路由函数参数中直接使用,无需额外定义Pydantic模型,保持原有开发体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:33:21