我有以下的FastAPI后端:
问题在于当我向这个API发送带有额外数据的请求时,会出现以下情况:
from fastapi import FastAPI
app = FastAPI
class Demo(BaseModel):
content: str = None
@app.post("/demo")
async def demoFunc(d:Demo):
return d.content
问题在于当我向这个API发送带有额外数据的请求时,会出现以下情况:
data = {"content":"some text here"}aaaa
或者
data = {"content":"some text here"aaaaaa}
resp = requests.post(url, json=data)
如果data = {"content":"some text here"}aaaa
,则会出现状态码为422不可处理的实体
的错误,返回字段中包含实际值("some text here")和额外数据("aaaaa")。
{
"detail": [
{
"loc": [
"body",
47
],
"msg": "Extra data: line 4 column 2 (char 47)",
"type": "value_error.jsondecode",
"ctx": {
"msg": "Extra data",
"doc": "{\n \"content\": \"some text here\"}aaaaa",
"pos": 47,
"lineno": 4,
"colno": 2
}
}
]
}
我尝试将app=FastAPI()
这行代码放在try-catch块中,但是它并没有起作用。有没有办法处理这个问题并自定义响应而不是使用上述的自动响应呢?类似于下面这样:
{"error": {"message": "Invalid JSON body"},
"status": 0}