API传大数据遇413错误,如何用POST请求体以application/octet-stream流式传输?
解决方案:流式传输绕过413错误
完全可以通过application/octet-stream的方式流式传输数据,避免一次性发送超大请求体触发413限制。核心思路是客户端分块发送数据,服务端分块接收处理,不会将整个请求体加载到内存中。
FastAPI 服务端实现
服务端通过Request对象流式读取请求体,分块处理数据:
from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.post("/stream-data") async def handle_stream(request: Request): # 分块接收数据 data_buffer = [] async for chunk in request.stream(): data_buffer.append(chunk) # 合并数据并执行业务逻辑(示例为转字符串,按需调整) full_data = b"".join(data_buffer).decode("utf-8") # 这里替换成你的实际数据处理代码 processed_result = {"received_data_size": len(full_data), "status": "processed"} return JSONResponse(content=processed_result)
Python Requests 客户端实现
客户端通过生成器分块生成/读取数据,流式发送请求:
import requests def stream_large_data(): # 模拟生成大量数据,实际场景可替换为读取大文件的块 for idx in range(1000): yield f"Batch {idx}: {idx*1000} lines of data\n".encode("utf-8") # 目标接口地址 api_url = "http://localhost:8000/stream-data" # 指定Content-Type为application/octet-stream headers = {"Content-Type": "application/octet-stream"} # 流式发送请求 response = requests.post(api_url, data=stream_large_data(), headers=headers) print("服务端响应:", response.json())
关键注意事项
- 数据格式兼容:因为使用二进制流传输,你需要自定义数据的序列化/反序列化规则(比如原本的JSON可以拆分为多行JSON块,服务端接收后逐行解析)。
- 二进制数据适配:如果传输的是二进制文件(如图片、压缩包),直接读取文件的二进制块发送即可,无需编码为UTF-8。
- 服务端配置:FastAPI默认支持流式请求,无需额外修改配置。
内容的提问来源于stack exchange,提问作者sureshhewabi
相关产品推荐
相关产品推荐

