跳至内容

后台任务 - BackgroundTasks

你可以在路径操作函数或依赖项函数中声明一个类型为BackgroundTasks的参数,然后你可以使用它在响应发送后调度后台任务的执行。

你可以直接从fastapi中导入它

from fastapi import BackgroundTasks

fastapi.BackgroundTasks

BackgroundTasks(tasks=None)

基类:BackgroundTasks

一系列后台任务,它们将在响应发送给客户端后被调用。

FastAPI 文档中的后台任务中了解更多信息。

示例

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"}
参数 描述
tasks

类型: Sequence[BackgroundTask] | None 默认值: None

starlette/background.py 中的源代码
32
33
def __init__(self, tasks: typing.Sequence[BackgroundTask] | None = None):
    self.tasks = list(tasks) if tasks else []

func 实例属性

func = func

args 实例属性

args = args

kwargs 实例属性

kwargs = kwargs

is_async 实例属性

is_async = is_async_callable(func)

tasks 实例属性

tasks = list(tasks) if tasks else []

add_task

add_task(func, *args, **kwargs)

在响应发送后,添加一个将在后台调用的函数。

FastAPI 文档中的后台任务中了解更多信息。

参数 描述
func

将在响应发送后调用的函数。

它可以是普通的def函数或async def函数。

类型: Callable[P, Any]

*args

类型: args 默认值: ()

**kwargs

类型: kwargs 默认值: {}

fastapi/background.py 中的源代码
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def add_task(
    self,
    func: Annotated[
        Callable[P, Any],
        Doc(
            """
            The function to call after the response is sent.

            It can be a regular `def` function or an `async def` function.
            """
        ),
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None:
    """
    Add a function to be called in the background after the response is sent.

    Read more about it in the
    [FastAPI docs for Background Tasks](https://fastapi.org.cn/tutorial/background-tasks/).
    """
    return super().add_task(func, *args, **kwargs)