You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI优化:如何配置服务10秒后中断请求连接?

正确配置请求超时的方法

你对gunicorn --timeout 参数的理解是对的,这个参数用于控制worker进程的存活超时(如果worker在指定时间内没有响应master的心跳,会被强制重启),和单个请求的处理时长限制无关。要实现请求发起10秒后主动中断连接,需要针对uvicorn worker配置请求级超时,具体有两种方式:

方式一:通过gunicorn传递uvicorn参数

因为你使用的是uvicorn.workers.UvicornWorker,可以用gunicorn的--worker-args参数给uvicorn传递请求超时配置。修改后的启动命令如下:

command=gunicorn -w 3 -k uvicorn.workers.UvicornWorker --worker-args="--timeout 10"

这里uvicorn的--timeout参数就是单个请求的处理超时阈值,一旦请求处理超过10秒,uvicorn会主动中断连接。

方式二:应用框架层面添加超时中间件(适用于FastAPI/Starlette)

如果你的后端基于FastAPI或Starlette框架,也可以通过添加中间件实现请求超时控制,示例代码如下:

from fastapi import FastAPI, Request
from fastapi.responses import Response
import asyncio

app = FastAPI()

@app.middleware("http")
async def timeout_middleware(request: Request, call_next):
    try:
        return await asyncio.wait_for(call_next(request), timeout=10)
    except asyncio.TimeoutError:
        return Response(content="请求超时", status_code=408)

这种方式更灵活,可针对不同路由设置不同超时,但如果需要全局统一的服务端中断逻辑,方式一的配置更直接。

内容的提问来源于stack exchange,提问作者qwerttttq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:00:54