Optimizing FastAPI with Multiple Workers for Background Tasks
Last Updated :
12 Dec, 2023
A modern web-framework in Python which is used for building APIs is called FastAPI. There are some circumstances when the user wants a specific action to be performed in the background after the raise of a request. This is possible by utilizing multiple workers in a background task while using FastAPI. In this article, we will discuss the same.
FastAPI with Multiple Workers for Background Tasks
Syntax: background_tasks.add_task(function_background)
Here,
- function_background: It is the function to be called for a background task to be performed.
In this example, we have created two functions call_main_task and call_background_task. The call_main_task will be called when the user requests for /app, while the call_background_task will be called automatically on the call of the call_main_task.
main.py: In this file, have imported BackgroundTasks and called FastAPI task using Pydantic.
Python3
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
@app .get( "/app" )
async def call_main_task(background_tasks: BackgroundTasks):
background_tasks.add_task(call_background_task)
return "Main task called!"
def call_background_task():
print (f "Background Task called!" )
|
Output
For starting the FastAPI app, use the following code in terminal. This is the place where you will see the background task being performed.
uvicorn main:app --reload
For calling the value returned from main app function, we use the following code in test file:
test.py: The code sends a GET request to “http://127.0.0.1:8000/app” and expects a JSON response from the FastAPI route defined at “/app”. It then prints the JSON response to the console.
Pycharm Output
Browser Output
Share your thoughts in the comments
Please Login to comment...