使用 python 'aiohttp' 发送文件产生 "There was an error parsing the body"
Sending files using python 'aiohttp' produce "There was an error parsing the body"
我正在尝试让两个服务进行通信。第一个 API 暴露给用户。
第二个是隐藏的,可以处理文件。所以第一个可以重定向请求。
我想使用 aiohttp 处理 post 异步请求,但我遇到了这个错误:“解析正文时出错”
重现错误:
假设这是服务器代码
from fastapi import FastAPI
from fastapi import UploadFile, File
app = FastAPI()
@app.post("/upload")
async def transcript_file(file: UploadFile = File(...)):
pass
这是客户端代码:
from fastapi import FastAPI
import aiohttp
app = FastAPI()
@app.post("/upload_client")
async def async_call():
async with aiohttp.ClientSession() as session:
headers = {'accept': '*/*',
'Content-Type': 'multipart/form-data'}
file_dict = {"file": open("any_file","rb")}
async with session.post("http://localhost:8000/upload", headers=headers, data=file_dict) as response:
return await response.json()
描述:
- 运行 服务器在 8000 端口,客户端在任意端口
- 打开浏览器,在客户端打开文档。
- 执行post请求,看到错误
环境:
- aiohttp = 3.7.4
- fastapi = 0.63.0
- uvicorn = 0.13.4
- python-多部分=0.0.2
Python版本:3.8.8
从这个answer:
If you are using one of multipart/*
content types, you are actually required to specify the boundary parameter in the Content-Type
header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.
您需要去掉Content-Type
头的显式设置,客户端aiohttp
会为您隐式添加,包括boundary
参数。
我正在尝试让两个服务进行通信。第一个 API 暴露给用户。 第二个是隐藏的,可以处理文件。所以第一个可以重定向请求。 我想使用 aiohttp 处理 post 异步请求,但我遇到了这个错误:“解析正文时出错”
重现错误: 假设这是服务器代码
from fastapi import FastAPI
from fastapi import UploadFile, File
app = FastAPI()
@app.post("/upload")
async def transcript_file(file: UploadFile = File(...)):
pass
这是客户端代码:
from fastapi import FastAPI
import aiohttp
app = FastAPI()
@app.post("/upload_client")
async def async_call():
async with aiohttp.ClientSession() as session:
headers = {'accept': '*/*',
'Content-Type': 'multipart/form-data'}
file_dict = {"file": open("any_file","rb")}
async with session.post("http://localhost:8000/upload", headers=headers, data=file_dict) as response:
return await response.json()
描述:
- 运行 服务器在 8000 端口,客户端在任意端口
- 打开浏览器,在客户端打开文档。
- 执行post请求,看到错误
环境:
- aiohttp = 3.7.4
- fastapi = 0.63.0
- uvicorn = 0.13.4
- python-多部分=0.0.2
Python版本:3.8.8
从这个answer:
If you are using one of
multipart/*
content types, you are actually required to specify the boundary parameter in theContent-Type
header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.
您需要去掉Content-Type
头的显式设置,客户端aiohttp
会为您隐式添加,包括boundary
参数。