It is imported/included directly into FastAPI so that you can import it from fastapi and avoid accidentally importing the alternative BackgroundTask (without the s at the end) from starlette.background.īy only using BackgroundTasks (and not BackgroundTask), it's then possible to use it as a path operation function parameter and have FastAPI handle the rest for you, just like when using the Request object directly. The class BackgroundTasks comes directly from starlette.background.
If there was a query in the request, it will be written to the log in a background task.Īnd then another background task generated at the path operation function will write a message using the email path parameter. In this example, the messages will be written to the log.txt file after the response is sent.
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