在FastAPI中,我试图理解为什么后台实例没有在路由函数处理程序外部创建,以及它的不同行为.
Examples:个
标准文档示例按预期工作:
@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"
在路由函数之外添加BACKGROUND_TASKS时,它的行为有所不同:
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"
同时,如果我们try 在some_logic
函数中初始化BackgroundTasks
,则任务不会按如下方式运行:
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"
为什么这三个 case 会有所不同?为什么我需要将后台任务从路由函数传递到下面调用的函数?