【问题标题】:Sending files using python 'aiohttp' produce "There was an error parsing the body"使用 python 'aiohttp' 发送文件会产生“解析正文时出错”
【发布时间】:2021-05-31 15:26:23
【问题描述】:

我正在尝试让两个服务进行通信。第一个 API 向用户公开。 第二个是隐藏的,可以处理文件。所以第一个可以重定向请求。 我想使用 aiohttp 使发布请求异步,但我遇到了这个错误:“解析正文时出错”

要重新创建错误: 假设这是服务器代码

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-multipart = 0.0.2

Python 版本:3.8.8

【问题讨论】:

    标签: python python-3.x aiohttp fastapi


    【解决方案1】:

    来自answer

    如果您使用multipart/* 的内容类型之一,实际上需要在Content-Type 标头中指定边界参数,否则服务器(在HTTP 请求的情况下)将无法解析有效载荷。

    您需要去掉Content-Type标头的显式设置,客户端aiohttp会为您隐式添加,包括boundary参数。

    【讨论】:

    • 你是救生员!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2021-10-05
    • 1970-01-01
    • 2011-10-02
    相关资源
    最近更新 更多