后台任务¶
你可以定义在返回响应 之后 运行的后台任务。
这对于需要在请求之后执行操作,但客户端不必在接收响应前等待操作完成的情况非常有用。
例如,这包括:
- 执行操作后发送电子邮件通知:
- 由于连接电子邮件服务器并发送电子邮件通常很“慢”(几秒钟),你可以立即返回响应并在后台发送电子邮件通知。
- 处理数据:
- 例如,假设你收到一个必须经过缓慢处理的文件,你可以返回一个“已接受”(HTTP 202)响应并在后台处理该文件。
使用 BackgroundTasks¶
首先,导入 BackgroundTasks 并在你的路径操作函数中定义一个类型声明为 BackgroundTasks 的参数:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
FastAPI 将为你创建类型为 BackgroundTasks 的对象,并将其作为该参数传递。
创建任务函数¶
创建一个将作为后台任务运行的函数。
它只是一个可以接收参数的标准函数。
它可以是一个 async def 或普通的 def 函数,FastAPI 会知道如何正确处理它。
在这种情况下,任务函数将写入文件(模拟发送电子邮件)。
并且由于写入操作不使用 async 和 await,我们使用普通的 def 定义函数:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
添加后台任务¶
在你的路径操作函数内部,使用 .add_task() 方法将你的任务函数传递给后台任务对象:
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_notification(email: str, message=""):
with open("log.txt", mode="w") as email_file:
content = f"notification for {email}: {message}"
email_file.write(content)
@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
.add_task() 接收以下参数:
- 一个要在后台运行的任务函数 (
write_notification)。 - 应按顺序传递给任务函数的任意参数序列 (
email)。 - 应传递给任务函数的任意关键字参数 (
message="some notification")。
依赖注入¶
使用 BackgroundTasks 也可以与依赖注入系统协同工作,你可以在多个层级声明 BackgroundTasks 类型的参数:在路径操作函数中、在依赖项(可依赖对象)中、在子依赖项中等。
FastAPI 知道在每种情况下该做什么以及如何重用同一个对象,以便所有后台任务被合并在一起并在之后在后台运行:
from typing import Annotated
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: str | None = None):
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
return q
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
):
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}
🤓 Other versions and variants
from typing import Annotated, Union
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
return q
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
):
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}
from typing import Union
from fastapi import BackgroundTasks, Depends, FastAPI
from typing_extensions import Annotated
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
return q
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: Annotated[str, Depends(get_query)]
):
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}
Tip
Prefer to use the Annotated version if possible.
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: str | None = None):
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
return q
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
):
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}
Tip
Prefer to use the Annotated version if possible.
from typing import Union
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
def get_query(background_tasks: BackgroundTasks, q: Union[str, None] = None):
if q:
message = f"found query: {q}\n"
background_tasks.add_task(write_log, message)
return q
@app.post("/send-notification/{email}")
async def send_notification(
email: str, background_tasks: BackgroundTasks, q: str = Depends(get_query)
):
message = f"message to {email}\n"
background_tasks.add_task(write_log, message)
return {"message": "Message sent"}
在这个例子中,消息将在响应发送之后被写入 log.txt 文件。
如果请求中包含查询参数,它将在后台任务中被写入日志。
然后,在路径操作函数中生成的另一个后台任务将使用 email 路径参数写入一条消息。
技术细节¶
BackgroundTasks 类直接来自 starlette.background。
它被直接导入/包含到 FastAPI 中,以便你可以从 fastapi 导入它,并避免意外地从 starlette.background 导入替代的 BackgroundTask(末尾没有 s)。
通过仅使用 BackgroundTasks(而不是 BackgroundTask),可以将其用作路径操作函数参数,并让 FastAPI 为你处理其余的事情,就像直接使用 Request 对象一样。
在 FastAPI 中仍然可以单独使用 BackgroundTask,但你必须在代码中创建对象,并返回一个包含它的 Starlette Response。
你可以在 Starlette 官方的后台任务文档 中查看更多细节。
注意事项¶
如果你需要执行繁重的后台计算,并且不一定需要由同一个进程运行(例如,你不需要共享内存、变量等),你可能会受益于使用其他更强大的工具,如 Celery。
它们往往需要更复杂的配置、一个消息/作业队列管理器(如 RabbitMQ 或 Redis),但它们允许你在多个进程中运行后台任务,尤其是在多个服务器上。
但是,如果你需要访问同一个 FastAPI 应用程序的变量和对象,或者你需要执行小的后台任务(如发送电子邮件通知),你可以简单地使用 BackgroundTasks。
回顾¶
导入并使用 BackgroundTasks,在路径操作函数和依赖项中通过参数添加后台任务。