我正在编写一个带有字节主体的python post请求:
with open('srt_file.srt', 'rb') as f:
data = f.read()
res = requests.post(url='http://localhost:8000/api/parse/srt',
data=data,
headers={'Content-Type': 'application/octet-stream'})
在服务器部分,我尝试解析正文:
app = FastAPI()
BaseConfig.arbitrary_types_allowed = True
class Data(BaseModel):
data: bytes
@app.post("/api/parse/{format}", response_model=CaptionJson)
async def parse_input(format: str, data: Data) -> CaptionJson:
...
然而,我得到了422错误:{"detail":[{"loc":["body"],"msg":"value is not a valid dict","type":"type_error.dict"}]}
那么,我的代码哪里出了问题,我应该如何修复它?提前感谢大家的帮助!!
发布于 2021-08-08 15:26:12
默认情况下,FastAPI会希望你传递json,它会解析成一个字典。如果不是json,它就不能这样做,这就是为什么你会得到你看到的错误。
您可以使用Request
对象来接收来自POST正文的任意字节。
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/foo")
async def parse_input(request: Request):
data: bytes = await request.body()
# Do something with data
您可以考虑使用Depends
,它将允许您清理您的路由函数。FastAPI将首先调用依赖函数(本例中为parse_body
),并将其作为参数注入到路由函数中。
from fastapi import FastAPI, Request, Depends
app = FastAPI()
async def parse_body(request: Request):
data: bytes = await request.body()
return data
@app.get("/foo")
async def parse_input(data: bytes = Depends(parse_body)):
# Do something with data
pass
发布于 2021-08-08 14:59:09
如果您的请求的最终目标是只发送字节,那么请查看FastAPI的文档以接受类似字节的对象:https://fastapi.tiangolo.com/tutorial/request-files。
不需要将字节封装到模型中。
https://stackoverflow.com/questions/68701240
复制相似问题