如何仅在 FastAPI 中完成所有后台任务后才发送响应

How to send a response only after all background tasks are completed in FastAPI

在 Mac 上使用 python 3 倍。 我有一个带有一个端点的 FastAPI 服务器。 在这个端点,我希望能够 运行 一些后台任务。完成后,进行一些计算,然后才发送 HTTP 响应。

我有以下内容:

import asyncio

import uvicorn
from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


async def log(message: str):
    print(f"start to process message: {message}")
    if message == "aaaaa":
        await asyncio.sleep(10)
    else:
        await asyncio.sleep(3)
    print(f"processed {message}")


async def process():
    tasks = [log('aaaaa'),
             log('bbbbb')]
    print("start processing the tasks")
    await asyncio.gather(*tasks)
    print(" we are done with all the tasks")


@app.post("/upload-to-process")
async def upload(background_tasks: BackgroundTasks):
    background_tasks.add_task(process)

    return {"result": "all tasks are completed successfully successfully"}


if __name__ == "__main__":
    uvicorn.run(app, host="localhost", port=8001)

上面所做的是立即发送结果,而不是等待任务完成。

如何将上面的代码改成等到所有后台都完成后才发回响应?

等待 background 任务真的没有意义,因为根据定义它们是 运行 在后台。

如果你想要的是运行运行那些任务同步的功能,即不是在后台,您可以这样做:

@app.post("/upload-to-process")
async def upload(background_tasks: BackgroundTasks):
    await process()
    return {"result": "all tasks are completed successfully successfully"}

但是请注意,如果这些任务花费的时间太长(这取决于您的服务器配置请求时间限制,通常在 30 秒到 15 分钟之间),请求将会超时。