コンテンツにスキップ

バックグラウンドタスク - 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.dokyumento.jp/tutorial/background-tasks/).
    """
    return super().add_task(func, *args, **kwargs)