python data_error ai_generated true

运行时错误:请求体超过最大大小(1000000字节)

RuntimeError: Request body exceeded maximum size (1000000 bytes)

ID: python/fastapi-request-body-too-large

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2024-07-05首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

传入的请求体大于应用设置的最大允许大小。

English

The incoming request body is larger than the maximum allowed size set by the application.

generic

解决方案

  1. 90% 成功率 Increase the maximum request body size
    from starlette.middleware.base import BaseHTTPMiddleware
    class LimitUploadSize(BaseHTTPMiddleware):
        async def dispatch(self, request, call_next):
            if request.headers.get('content-length'):
                if int(request.headers['content-length']) > 10 * 1024 * 1024:
                    raise HTTPException(status_code=413, detail="Request too large")
            return await call_next(request)
    app.add_middleware(LimitUploadSize)
  2. 80% 成功率 Use streaming to handle large bodies
    async def upload():
        async for chunk in request.stream():
            process_chunk(chunk)

无效尝试

常见但无效的做法:

  1. Truncating the request body on the client side 60% 失败

    May lose data; not a server-side fix.

  2. Ignoring the error and retrying 95% 失败

    Same error will occur until limit is increased or body is reduced.