后台任务 - 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 |
|