バックグラウンドタスク - 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
|
型: |
ソースコードはstarlette/background.py
にあります
32 33 |
|
add_task ¶
add_task(func, *args, **kwargs)
レスポンスが送信された後にバックグラウンドで呼び出される関数を追加します。
詳細については、FastAPIのバックグラウンドタスクに関するドキュメントを参照してください。
パラメータ | 説明 |
---|---|
func
|
レスポンスが送信された後に呼び出される関数。 通常の
種類: |
*args
|
種類: |
**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 |
|