这个
BackgroundTasks
实例由FastAPI框架填充并注入到调用者中。在第一个示例中,您使用的路由具有由FastAPI注入的依赖项。
第二个示例,您正在调用
some_logic
作为正常功能。因为它不是由FastAPI直接调用的,所以没有发生依赖注入。
在第三个示例中,您创建了一个新的后台任务实例,但这与FastAPI关心的实例不同。您在其中创建任务,但没有注册处理程序来对其执行操作。
在这种情况下,如果目标是使后台任务更容易应用于方法,则可以添加
某些逻辑
作为路由的依赖项。FastAPI调用依赖项,因此将注入参数。
示例:
from fastapi import FastAPI, Depends
from starlette.background import BackgroundTasks
from starlette.testclient import TestClient
app = FastAPI()
def task():
print("Hello from the Background!")
async def some_logic(background_tasks: BackgroundTasks):
background_tasks.add_task(task)
@app.get('/', dependencies=[Depends(some_logic)])
async def index():
return "Hello"
with TestClient(app) as client:
client.get("/")
Hello from the Background!