我按照文档使用FastAPI将后台任务添加到Azure Function App:
async def background_task():
logging.info("Background task started")
await asyncio.sleep(5)
logging.info("Background task finished")
@app.get("/do_background_task")
async def do_background_task(background_tasks: BackgroundTasks):
background_tasks.add_task(background_task)
return {"message": "Background task started, this response should return immediately."}
但是并没有按预期工作,5秒后才返回响应。
为了重现这一点,我分叉了 Microsoft FastAPI 示例存储库并添加了上面的代码。可以在here找到带有复制案例的分叉存储库。
在本地和 Azure 上运行时都会失败。这是 Azure Functions 的限制还是我做错了什么?
但是并没有按预期工作,5秒后才返回响应。
是的,如果您使用以下代码,这是预期的行为。一旦所有后台任务完成,
BackgroundTasks
就会返回响应。在这种情况下,它将在睡眠时间 5 秒后返回消息。
async def background_task():
logging.info("Background task started")
await asyncio.sleep(5)
logging.info("Background task finished")
@app.get("/do_background_task")
async def do_background_task(background_tasks: BackgroundTasks):
background_tasks.add_task(background_task)
return {"message": "Background task started, this response should return immediately."}
输出-
后台任务已完成 睡眠时间 5 秒后出现消息。这就是为什么您在获取返回消息时遇到 5 秒的延迟“后台任务已启动,此响应应立即返回。”.
我使用下面的代码来获得即时响应。
def send_notification(message):
logging.info(f'Notification will be sent over. Message: {message}')
def add_some_tasks(background_tasks: BackgroundTasks, message: str):
background_tasks.add_task(send_notification, message=message)
@app.get("/{msg}")
def send_msg(msg: str, background_tasks: BackgroundTasks):
add_some_tasks(background_tasks, message=msg)
return {"message": "Request has been successfully submitted."}
输出-
我立即得到了预期的回复。
传送门-