バックグラウンドタスク - 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"}
starlette/background.py
のソースコード
32 33 |
|
add_task ¶
add_task(func, *args, **kwargs)
レスポンス送信後にバックグラウンドで呼び出される関数を追加します。
FastAPIのバックグラウンドタスクに関するドキュメントで詳細を読むことができます。
パラメータ | 説明 |
---|---|
func
|
レスポンス送信後に呼び出す関数。 通常の
型: |
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 |
|