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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步