Kos*_*bre 8 python python-3.x starlette pydantic fastapi
我想创建一个 FastAPI 端点,它只接受一个任意的 post 请求正文并返回它。
如果我发送{"foo" : "bar"},我想{"foo" : "bar"}回来。但我也希望能够发送{"foo1" : "bar1", "foo2" : "bar2"}并取回。
我试过:
from fastapi import FastAPI
app = FastAPI()
app.post("/")
async def handle(request: BaseModel):
return request
Run Code Online (Sandbox Code Playgroud)
但是无论我发送什么,它都会返回一个空字典。
有任何想法吗?
Gab*_*lli 13
您可以使用类型提示 Dict[Any, Any] 告诉 FastAPI 您需要任何有效的 JSON:
from typing import Any, Dict
from fastapi import FastAPI
app = FastAPI()
@app.post("/")
async def handle(request: Dict[Any, Any]):
return request
Run Code Online (Sandbox Code Playgroud)
Ben*_*ida 10
只要输入包含在字典中,接受的答案就有效。即:以 a 开头{,以 a 结尾}。但是,这并不涵盖所有有效的 JSON 输入。例如,以下有效的 JSON 输入将失败:
true/false1.2null"text"[1,2,3]为了让端点接受真正通用的 JSON 输入,可以执行以下操作:
from typing import Any, Dict, List, Union
from fastapi import FastAPI
app = FastAPI()
@app.post("/")
async def handle(request: Union[List,Dict,Any]=None):
return request
Run Code Online (Sandbox Code Playgroud)
由于某种原因,仅仅使用Any不起作用。当我使用它时,FastApi 期望来自查询参数的输入,而不是来自请求正文的输入。
这=None使它接受null并且也是一个空的身体。您可以保留该部分,然后请求正文将被要求不为空/空。
如果您使用的是Python3.10,那么您可以去掉Union并将定义写为:
async def handle(request: List | Dict | Any = None):
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2636 次 |
| 最近记录: |