Hintergrundtasks – BackgroundTasks
¶
Sie können einen Parameter in einer Pfadoperation-Funktion oder einer Abhängigkeitsfunktion mit dem Typ BackgroundTasks
deklarieren und diesen danach verwenden, um die Ausführung von Hintergrundtasks nach dem Senden der Response zu definieren.
Sie können BackgroundTasks
direkt von fastapi
importieren:
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
34 35 |
|
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 |
|