使用python'aiohttp'发送文件产生“解析正文时出错"; [英] Sending files using python 'aiohttp' produce "There was an error parsing the body"

查看:56
本文介绍了使用python'aiohttp'发送文件产生“解析正文时出错";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to make two services communicate. The first API is exposed to the user. The second is hidden and can process files. So the first can redirect requests. I want to make of the post request asynchronus using aiohttp but i am facing this error : "There was an error parsing the body"

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

To recreate the error : Lets say this is the server code

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 version: 3.8.8

推荐答案

从此答案:

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

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

You need to remove the explicit setting of the Content-Type header, the client aiohttp will add it implicitly for you, including the boundary parameter.

这篇关于使用python'aiohttp'发送文件产生“解析正文时出错";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆