fastapi设置超时时间

发布时间 2023-10-21 11:00:48作者: bitterteaer

方法一:应用级别的超时设置

一种设置 FastAPI 应用程序全局超时时间的方法是使用TimeoutMiddleware中间件。以下是一个示例:

from fastapi import FastAPI
from fastapi.middleware.timeout import TimeoutMiddleware
from datetime import timedelta

app = FastAPI()

# 设置应用程序的默认超时时间为5秒
app.add_middleware(TimeoutMiddleware, timeout=timedelta(seconds=5))

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

方法二:路由级别的超时设置

如果你希望为特定路由设置不同的超时时间,可以在路由处理函数中使用timeout参数。以下是一个示例:

from fastapi import FastAPI
from datetime import timedelta

app = FastAPI()

@app.get("/slow_endpoint")
async def slow_endpoint():
    return {"message": "This is a slow endpoint."}

@app.get("/fast_endpoint", timeout=timedelta(seconds=2))
async def fast_endpoint():
    return {"message": "This is a fast endpoint."}