本文介绍在 azure function 等有执行时间限制的环境中,如何将耗时的 cosmos db 批量写入操作移至后台线程执行,避免超时失败,并支持异常通知。核心方案是使用 `threading.thread` 启动非阻塞任务,同时兼顾错误捕获与可观测性。
在 Python Web 或 Serverless 场景(如 Azure Functions)中,当需要向 Cosmos DB 写入大量数据时,常因单次调用耗时过长(>2 分钟)触发平台超时而失败。此时,不能简单用 asyncio 包裹同步 I/O 方法(如示例中的 storeDataToDb()),因为 asyncio.run() 会阻塞等待协程完成,而该方法本身是同步阻塞的(含 time.sleep()),根本未实现真正异步——这也是原代码仍卡住的根本原因。
✅ 正确解法:使用多线程(threading.Thread)
Cosmos DB 写入属于典型的 I/O 密集型操作,Python 的 GIL 不会成为瓶颈,线程是轻量、安全且高效的选择:
from threading import Thread
import logging
def import_and_background_task(myobj):
"""启动后台线程执行 DB 写入,立即返回"""
def _safe_store():
try:
myobj.storeDataToDb()
except Exception as e:
logging.error(f"Background DB write failed: {e}")
# ✅ 此处可集成邮件发送逻辑,例如:
# send_failure_email(f"DB update failed for {myobj.id}: {str(e)}")
thread = Thread(target=_safe_store, name="CosmosDB-Writer")
thread.daemon = False # 关键:设为非守护线程,确保其能完整执行
thread.start()
logging.info("Background DB write started. Returning response immediately.")
def executeReport():
myobj.readInputFile()
myobj.readDataFromDb()
myobj.generateReport()
# 启动后台写入 → 不等待!
import_and_background_task(myobj)
print('Response sent immediately — background task is running.')
return {"success": True}
⚠️ 注意事项与最佳实践: