If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like Celery. You can see more details in Starlette's official docs for Background Tasks. It's still possible to use BackgroundTask alone in FastAPI, but you have to create the object in your code and return a Starlette Response including it. 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
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |