FastAPI:使用repeat_every定时执行PUT端点遇问题,求正确实现方式
你的实现方式不正确,问题出在装饰器的混用
你把API端点装饰器@app.put、启动事件装饰器@app.on_event("startup")和重复任务装饰器@repeat_every堆在了同一个函数上,这会导致FastAPI无法正确识别这个函数的作用:
- 作为API端点,这个函数没有对应处理HTTP请求的逻辑,调用时自然返回Null
- 作为后台重复任务,装饰器的组合方式错误,导致任务根本没启动,所以看不到重复执行的日志
正确的实现思路
把后台定期任务和API端点拆成两个独立的函数:
- 后台任务:用
@app.on_event("startup")和@repeat_every装饰,负责定期获取数据并存储(比如存在全局变量、数据库里) - API端点:单独用
@app.put装饰,负责返回最新存储的数据
示例代码
from fastapi import FastAPI from fastapi_utils.tasks import repeat_every from pydantic import BaseModel from typing import List # 假设你的Fuellstand模型和get_fuellstand函数定义如下 class FuellstandEntry(BaseModel): lane_id: int level: float class Fuellstand(BaseModel): __root__: List[FuellstandEntry] def get_fuellstand(lanes): # 模拟数据获取逻辑 return [FuellstandEntry(lane_id=lane, level=50.0) for lane in lanes] app = FastAPI() lanes = [1,2,3] # 用全局变量存储最新油位数据(生产环境建议用数据库或缓存) latest_fuellstand = None # 后台定期更新数据的任务 @app.on_event("startup") @repeat_every(seconds=15) # 设置为你需要的15秒间隔 def update_fuellstand(): global latest_fuellstand liste = get_fuellstand(lanes) latest_fuellstand = Fuellstand(__root__=liste) print("油位数据已更新") # 控制台打印,验证任务执行状态 # 独立的PUT API端点 @app.put('/fuellstand', response_model=Fuellstand) def return_fuellstand(): # 返回最新存储的数据 return latest_fuellstand
补充说明
- 后台任务
update_fuellstand会在服务启动后,每15秒自动执行一次,更新latest_fuellstand的值 - 调用
/fuellstand端点时,会直接返回最新的latest_fuellstand数据 - 如果需要保证端点调用时必有数据,可以在服务启动时先初始化一次
latest_fuellstand,比如在启动事件里单独执行一次数据获取逻辑
内容的提问来源于stack exchange,提问作者Lukas Scholz
相关产品推荐
相关产品推荐

