【问题标题】:enforce path contraints with fastapi使用 fastapi 强制执行路径约束
【发布时间】:2021-12-09 12:22:38
【问题描述】:

在快速 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

【问题讨论】:

    标签: python fastapi pydantic


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-05
      • 1970-01-01
      • 2014-03-04
      • 2018-03-07
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多