使用 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()

描述

环境

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参数。