在 FastAPI 框架中,pydantic 错误消息如下所示。
{"detail": [
{
"loc": [
"body",
"location",
"name"
],
"msg": "field required",
"type": "value_error.missing"
},
{
"loc": [
"body",
"location",
"name12"
],
"msg": "extra fields not permitted",
"type": "value_error.extra"
}
]
}
我想发送一个简单的消息:
{"field-name":"error message"}
.在他们提到的 Pydantic 文档中,在 try: except 块中创建一个模型实例并在 except 块中构造错误消息。但是在快速 API 中,由 fastapi 本身创建的模型实例,例如,如果我写一个像下面这样的 URL
@router.post("/", response_model=DataModelOut)
async def create_location(location: schemas.LocationIn, user: str = Depends(get_current_user) ):
return model.save(location,user)
这里fastapi本身创建的位置实例就是问题所在。
有没有办法构造错误消息?
最佳答案
实际上这个错误信息来自 fastapi.exceptions
,您可以通过覆盖自定义异常来实现这一点,
想象一下我有这样的简单应用程序:
from fastapi import Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=jsonable_encoder({"detail": exc.errors(),
"body": exc.body,
"your_additional_errors": {"Will be": "Inside", "This":" Error message"}}),
)
class Item(BaseModel):
title: str
size: int
@app.post("/items/")
async def create_item(item: Item):
return item
如果我将无效值发送到我的请求正文{
"title": 22,
"size": "hehe"
}
现在错误将更加个性化:{
"detail": [
{
"loc": [
"body",
"size"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
],
"body": {
"title": 22,
"size": "hehe"
},
"your_additional_errors": {
"Will be": "Inside the",
"Error": "Message"
}
}
您可以更改异常内容,一切由您决定。
关于python - 是否可以更改 fastAPI 中的 pydantic 错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60274141/