在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块中构造错误消息。但在fast API中,例如,如果我编写如下URL,则由fastapi本身创建的模型实例
@router.post("/", response_model=DataModelOut)
async def create_location(location: schemas.LocationIn, user: str = Depends(get_current_user) ):
return model.save(location,user)
在这里,由fastapi本身创建的location实例就是问题所在。
有什么方法可以构造错误消息吗?
发布于 2020-07-16 23:12:41
实际上,这个错误消息来自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"
}
}
您可以更改exception的内容,一切由您决定。
发布于 2020-02-18 14:15:47
我正在为它写一个中间件。
async def genrange(s):
import json
s = json.loads(s)
yield json.dumps({"message":{k.get("loc")[-1]:k.get("msg") for k in s['detail']},
"id":None})
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
response = await call_next(request)
status_code = response.status_code
if status_code >=300:
async for i in response.body_iterator:
data = genrange(i)
response.body_iterator = data
return response
https://stackoverflow.com/questions/60274141
复制相似问题