I have a FastAPI asynchronous task that I would like to run after returning from an endpoint. To do this, I am using BackgroundTasks; however, it seems that whilst the background task is running the main event loop is blocked.
async def simple_task():
await asyncio.sleep(10)
print("completed")
@router.post("/test")
async def test(background_tasks: BackgroundTasks):
background_tasks.add_task(simple_task)
return {"message": "Task started"}
In the above code, I am unable to hit any other endpoints on the swagger page whilst the background task is running.
If instead I don't use BackgroundTasks e.g.
@router.post("/test2")
async def test():
await asyncio.sleep(10)
return {"message": "Task started"}
Then I am able to hit other endpoints on the swagger page whilst the task is running.
Potentially I have a misunderstanding of how FastAPI/starlette BackgroundTasks work. I thought the BackgroundTask is kicked off on the main event loop thread, and since I am using an asynchronous function, the main event loop thread should be freed to respond to other requests.