使用 fastapi 强制执行路径约束

enforce path contraints with fastapi

我在快速使用正则表达式路径约束时遇到错误 api。

ValueError: On field "serial" the following field constraints are set but not enforced: regex. 
For more details see https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints

函数签名如下所示。

@devices.get("/{serial}", response_model=Device)
async def get_serial(serial: int = Path(..., regex=r"(?:\d{18}|\d{24})")) -> dict:

该错误将我指向 pydantic 文档,但我不明白哪里出了问题。我相信他们的建议正是 fastapi 应该在幕后做的事情。

https://pydantic-docs.helpmanual.io/usage/schema/#unenforced-field-constraints

由于您将字段限制为 int,因此无法对字段应用 regex 约束。而是将字段定义为 str,并且可以根据需要应用正则表达式:

async def get_serial(serial: str = Path(..., regex=r"(?:\d{18}|\d{24})")) -> dict:

这是因为 int 约束优先于 regex 约束,这是错误试图传达的内容。