后台任务 - BackgroundTasks
¶
你可以在*路径操作函数*或依赖函数中声明一个类型为 BackgroundTasks
的参数,然后你可以使用它来安排在响应发送后执行的后台任务。
你可以直接从 fastapi
导入它:
from fastapi import BackgroundTasks
fastapi.BackgroundTasks
¶
BackgroundTasks(tasks=None)
Bases: BackgroundTasks
A collection of background tasks that will be called after a response has been sent to the client.
Read more about it in the FastAPI docs for Background Tasks.
Example¶
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"}
PARAMETER | DESCRIPTION |
---|---|
tasks |
TYPE:
|
Source code in starlette/background.py
32 33 |
|
add_task
¶
add_task(func, *args, **kwargs)
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.
PARAMETER | DESCRIPTION |
---|---|
func |
The function to call after the response is sent. It can be a regular
TYPE:
|
*args |
TYPE:
|
**kwargs |
TYPE:
|
Source code in 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 |
|