gpt4 book ai didi

python - 使用 FastAPI 支持表单和 json 编码的主体

转载 作者:行者123 更新时间:2023-12-03 14:32:13 26 4
gpt4 key购买 nike

我一直在用 FastAPI创建一个基于 HTTP 的 API。它目前支持 JSON 编码的参数,但我也想支持 form-urlencoded (理想情况下甚至是 form-data )参数位于同一 URL。

关注 Nikita's answer我可以使用单独的网址:

from typing import Optional
from fastapi import FastAPI, Body, Form, Depends
from pydantic import BaseModel

class MyItem(BaseModel):
id: Optional[int] = None
txt: str

@classmethod
def as_form(cls, id: Optional[int] = Form(None), txt: str = Form(...)) -> 'MyItem':
return cls(id=id, txt=txt)

app = FastAPI()

@app.post("/form")
async def form_endpoint(item: MyItem = Depends(MyItem.as_form)):
print("got item =", repr(item))
return "ok"

@app.post("/json")
async def json_endpoint(item: MyItem = Body(...)):
print("got item =", repr(item))
return "ok"

我可以使用 curl 测试这些通过做:

curl -X POST "http://localhost:8000/form" -d 'txt=test'



curl -sS -X POST "http://localhost:8000/json" -H "Content-Type: application/json" -d '{"txt":"test"}'

似乎拥有一个接受两种内容类型并正确解析模型的 URL 会更好。但是上面的代码目前失败了:
{"detail":[{"loc":["body","txt"],"msg":"field required","type":"value_error.missing"}]}

或者
{"detail":"There was an error parsing the body"}

如果我发布到“错误”的端点,例如表单编码发布到 /json .

奖励积分;我也想支持 form-data似乎相关的编码参数(我的 txt 在实践中可能会变得很长),但如果它足够不同,可能需要将其变成另一个问题。

最佳答案

FastAPI 无法根据内容类型进行路由,您必须在请求中检查并正确解析:

@app.post('/')
async def route(req: Request) -> Response:
if req.headers['Content-Type'] == 'application/json':
item = MyItem(** await req.json())
elif req.headers['Content-Type'] == 'multipart/form-data':
item = MyItem(** await req.form())
elif req.headers['Content-Type'] == 'application/x-www-form-urlencoded':
item = MyItem(** await req.form())
return Response(content=item.json())

好像有开 issue在 GitHub 上关于此功能

关于python - 使用 FastAPI 支持表单和 json 编码的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61872923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com