In FastAPI, I'm trying to understand why the background instance not getting created outside the route function handler and its different behaviors.
Examples:
Standard doc example working as expected:
@app.get('/')
async def index(background_tasks: BackgroundTasks):
background_tasks.add_task(some_function_reference)
#Executes non-blocking in the same asyncio loop without any issues
return "Hello"
It behaves differently when adding the background_tasks outside of the route function:
async def some_logic(background_tasks: BackgroundTasks):
#Throws a "required positional argument missing" error
background_tasks.add_task(some_function_reference)
@app.get('/')
async def index():
await some_logic()
#Executes non-blocking in the same asyncio loop
return "Hello"
meanwhile, if we try to init the BackgroundTasks
in the some_logic
function, the task does not run as following:
async def some_logic():
#Does not Run
background_tasks = BackgroundTasks()
background_tasks.add_task(some_function_reference)
@app.get('/')
async def index(background_tasks: BackgroundTasks):
await some_logic()
#Executes non-blocking in the same asyncio loop
return "Hello"
Why would these three cases be different? Why do i need to pass the background tasks from the route function to the following called function?