为了能到远方,脚下的每一步都不能少.|

bitterteaer

园龄:3年8个月粉丝:1关注:0

fastapi设置超时时间

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

一种设置 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."}

本文作者:bitterteaer

本文链接:https://www.cnblogs.com/bitterteaer/p/17778623.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   bitterteaer  阅读(1980)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起