BackgroundTasks
A collection of background tasks that will be called after a response has been sent to the client. This is useful for operations that need to happen after the request but don’t need to block the response, such as sending emails, processing data, or logging.Methods
add_task
Add a function to be called in the background after the response is sent.Callable
required
The function to call after the response is sent. It can be a regular
def function or an async def function.Any
Positional arguments to pass to the function.
Any
Keyword arguments to pass to the function.
Usage Notes
- Background tasks are executed after the response has been sent to the client
- Both sync (
def) and async (async def) functions are supported - Tasks are executed in the order they are added
- Multiple tasks can be added to the same response
- Background tasks run in the same process, so they’re suitable for lightweight operations