如何使用 FastAPI 更改默认的 Pydantic 错误消息?

dat*_*ews 7 python pydantic fastapi

有什么办法可以改变 Pydantic 的默认响应"msg""message"

{
    "detail": [
        {
            "loc": [
                "body",
                "password"
            ],
            "msg": "Password should at least 8 characters long.",
            "type": "value_error"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

Gin*_*pin 5

这看起来像是一个 JSON 响应,而 Pydantic 本身并没有给出 的 JSON响应ValidationError。它应该只是一个常规的raise-​​dException像这样:

In [2]: from pydantic import BaseModel, constr

In [3]: class Credentials(BaseModel):
   ...:     password: constr(min_length=8)
   ...: 

In [4]: Credentials(password="xyz")
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Input In [4], in <cell line: 1>()
----> 1 Credentials(password="xyz")

...

ValidationError: 1 validation error for Credentials
password
  ensure this value has at least 8 characters (type=value_error.any_str.min_length; limit_value=8)
Run Code Online (Sandbox Code Playgroud)

我认为您正在使用 FastAPI(它具有 Pydantic 集成),并且当请求具有 时,此 JSON 响应实际上是 FastAPI 的内置错误响应ValidationError,如FastAPI 文档中有关处理错误的描述。我可以用这个例子复制类似的错误格式:

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel, constr

class Credentials(BaseModel):
    password: constr(min_length=8)

app = FastAPI()

@app.post("/login")
async def login(credentials: Credentials):
    print(credentials)  # This is just as an example!
    return JSONResponse(status_code=200)
Run Code Online (Sandbox Code Playgroud)
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel, constr

class Credentials(BaseModel):
    password: constr(min_length=8)

app = FastAPI()

@app.post("/login")
async def login(credentials: Credentials):
    print(credentials)  # This is just as an example!
    return JSONResponse(status_code=200)
Run Code Online (Sandbox Code Playgroud)

要更改响应正文,请查看 FastAPI 文档中的使用 RequestValidationError 正文,该文档显示您可以访问默认的detail错误列表,然后您可以编辑或复制到自定义详细信息列表,然后将其设置为contentJSON 错误的回复。

from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, constr

class Credentials(BaseModel):
    password: constr(min_length=8)

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    # Get the original 'detail' list of errors
    details = exc.errors()
    modified_details = []
    # Replace 'msg' with 'message' for each error
    for error in details:
        modified_details.append(
            {
                "loc": error["loc"],
                "message": error["msg"],
                "type": error["type"],
            }
        )
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": modified_details}),
    )


@app.post("/login")
async def login(credentials: Credentials):
    print(credentials)  # Just as an example!
    return JSONResponse(status_code=200)
Run Code Online (Sandbox Code Playgroud)
$ curl -s --header "Content-Type: application/json" --request POST --data '{"password":"xyz"}' http://localhost:8000/login | jq
{
  "detail": [
    {
      "loc": [
        "body",
        "password"
      ],
      "msg": "ensure this value has at least 8 characters",
      "type": "value_error.any_str.min_length",
      "ctx": {
        "limit_value": 8
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

当然,您也可以简单地定义自己的自定义contentJSONResponse.


归档时间:

查看次数:

20206 次

最近记录:

2 年,9 月 前