<!-- markdown css tag --><section id="nice" data-tool="mdnice编辑器" data-website="https://www.mdnice.com" style="; color: black; padding: 0 10px; line-height: 1.6; word-spacing: 0px; letter-spacing: 0px; word-break: break-word; word-wrap: break-word; text-align: left; font-family: PingFangSC-Light;"><figure data-tool="mdnice编辑器" style="margin: 0; margin-top: 10px; margin-bottom: 10px; display: flex; flex-direction: column; justify-content: center; align-items: center;"><img src="https://file.haoxueai.cn/haoxue/img/844b8d11-8e03-451b-a6f4-f52fde895ea4.png" alt style="max-width: 100%; border-radius: 0px 0px 5px 5px; display: block; margin: 20px auto; width: 85%; height: 100%; ob ject-fit: contain; box-shadow: #84A1A8 0px 10px 15px;"></figure>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">让 Python 代码并发执行早已不是难题:<code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.gather</code>、线程池、几个 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">await</code> 调用,一个下午就能搞定并行 I/O。真正困难、真正区分"demo"与"生产可用"的问题,是让一组<strong style="font-weight: border; color: rgb(248,57,41);">有界、有限的资源</strong>在并发下行为正确。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">这就是本文所说的<strong style="font-weight: border; color: rgb(248,57,41);">资源编排(resource orchestration)</strong>,也是一个当下非常及时的话题。Python 3.14 于 2025 年 10 月发布,是当前稳定基线,它专门为新支持的自由线程(free-threaded)构建,给 asyncio 带来了真正一等公民级别的线程安全改进。Python 3.15 在本文写作时已进入 beta,自 2026 年 5 月功能冻结、预计 10 月发布,它补上了结构化并发中长期存在的缺口——加入了类似取消作用域的能力,而 Trio、AnyIO 这类库早在 2018 年就已具备。本文只讲当前稳定的内容:核心技巧基于 3.11 及以上,仅第 5 节的内省工具明确要求 3.14。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">贯穿全文的场景是这样的:一个内部看板聚合器,需要并发查询四个后端服务——定价 API、持仓数据库、新闻流、风险模型——每个后端的真实容量和延迟特征都不同,而且要同时服务几十个用户。下面每个技巧都先在这套场景的可运行仿真中构建、测试过,给出真实测量数据,而非估算。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">前置要求:</p>
<ul data-tool="mdnice编辑器" style="margin-top: 8px; margin-bottom: 8px; padding-left: 25px; color: black; list-style-type: disc; ;">
<li><section style="margin-top: 5px; margin-bottom: 5px; line-height: 26px; text-align: left; color: rgb(1,1,1); font-weight: 500; ;">核心技巧需要 Python 3.11 或更新版本(第 5 节的内省工具需要 Python 3.14+)</section></li><li><section style="margin-top: 5px; margin-bottom: 5px; line-height: 26px; text-align: left; color: rgb(1,1,1); font-weight: 500; ;">代码无外部依赖,纯标准库</section></li></ul>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">1. 用 asyncio.TaskGroup 实现结构化并发</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;"><code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.gather</code> 有一个广为人知的失效模式:如果组内某个任务抛异常,其他任务不会自动取消;根据你 await 结果的方式,代码已经走过 gather 调用之后,后台可能还残留着孤立运行的任务。Python 3.11 引入的 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.TaskGroup</code> 从设计上修复了这一点。TaskGroup 内启动的每个任务,都保证在 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">async with</code> 块退出前要么完成、要么被取消;一旦某个任务失败,其余任务自动取消,而不是放任它们无人看管地继续跑。</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">build_dashboards_for_batch</span><span class="hljs-params" style="line-height: 26px;">(user_ids: list[str], enabled_backends: list[str])</span> -> list[dict]:</span><br> dashboards: list[dict] = []<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.TaskGroup() <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> tg:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">run_one</span><span class="hljs-params" style="line-height: 26px;">(uid: str)</span> -> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">None</span>:</span><br> dashboard = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> build_dashboard(uid, enabled_backends)<br> dashboards.append(dashboard)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> uid <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> user_ids:<br> tg.create_task(run_one(uid))<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> dashboards<br></code></pre>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">批次里每个用户都有自己的任务,<code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">async with</code> 块直到每一个任务结束或取消后才退出。这就是"结构化并发"里"结构化"的含义——组的生命周期直接绑定到代码块的生命周期,不可能意外地把任务泄漏到你以为一切都已完成的位置之后。</p>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">2. 用 asyncio.Semaphore 限制并发资源占用</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">TaskGroup 解决的是编排正确性,对容量只字未提。放任不管,上面的代码会同时向后端打开 30 条连接,而该后端实际只能扛住 3 条——本场景里的风险模型服务就是这样,超载就会崩溃。<code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.Semaphore</code> 就是解法,关键设计决策是作用域:<strong style="font-weight: border; color: rgb(248,57,41);">每个后端一个信号量,大小设为该后端的真实容量,在整个进程的所有并发请求间共享,而不是每个请求新建一个。</strong></p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;">_semaphores: dict[str, asyncio.Semaphore] = {<br> name: asyncio.Semaphore(cfg[<span class="hljs-string" style="color: #98c379; line-height: 26px;">"capacity"</span>]) <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> name, cfg <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> BACKEND_CONFIG.items()<br>}<br><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@asynccontextmanager</span><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">acquire_connection</span><span class="hljs-params" style="line-height: 26px;">(backend_name: str)</span>:</span><br> semaphore = _semaphores[backend_name]<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> semaphore:<br> conn = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> BackendConnection(backend_name).open()<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">yield</span> conn<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">finally</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> conn.close()<br></code></pre>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;"><code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">async with semaphore</code> 会阻塞任务直到有空位,退出时无论成功还是异常都自动释放——不需要手动 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">acquire()</code>/<code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">release()</code> 做容易出错的记账。因为信号量放在模块作用域、而不是每个请求内部新建,它跟踪的是整个批次下后端真实的并发容量,而不是单用户视角。我做过实测:并发发出 30 个看板请求、每个都打全部四个后端,然后测量每个后端实际峰值并发。容量被限制为 3 的风险模型后端,在飞峰下恰好稳定在同时 3 个在途调用,没有超过;其他后端则舒适地待在各自更高的上限内。信号量在真实突发负载下守住了边界。</p>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">3. 用 contextlib.AsyncExitStack 实现动态且有保证的清理</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">当你写代码时就确切知道要开多少个资源,堆叠 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">async with</code> 块没问题。但一旦这个数量变成运行时决定的——某用户启用哪些后端可能取决于功能开关、降级模式兜底、或按租户配置——你在函数真正运行前根本不知道数量是多少,堆叠写法就崩了。<code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">AsyncExitStack</code> 正好处理这种情况:它让你把任意数量、运行时才确定的异步上下文管理器开入一个栈,并保证栈退出时全部按相反顺序关闭。</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> AsyncExitStack() <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> stack:<br> connections = {<br> name: <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> stack.enter_async_context(acquire_connection(name))<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> name <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> enabled_backends<br> }<br> <span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># ... 使用 connections,无论最终有多少个</span><br></code></pre>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;"><code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">enter_async_context</code> 一步完成两件事:进入上下文管理器,并把它登记到栈里以便清理。因此一行字典推导就能打开数量真正可变的连接;无论最终是几个,当 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">async with AsyncExitStack()</code> 块退出时,每一个都保证被关闭。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">我做了两组测试:一次启用全部四个后端,确认四个连接都打开、都干净关闭、零泄漏;一次只启用四个中的两个(模拟运行时功能开关决策),确认恰好打开两个连接、另外两个后端完全没被触碰。清理顺序在这里也很重要——当资源之间存在依赖时,<strong style="font-weight: border; color: rgb(248,57,41);">逆序拆除</strong>才是正确行为,而 AsyncExitStack 自动给了你这一点,不用自己手写。</p>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">4. 用 asyncio.timeout() 传播截止时间</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;"><code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.wait_for</code> 过去是给单次调用设超时的标准做法,但它有个粗糙的棱角:用多个 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">wait_for</code> 包裹嵌套 await 很快就会变乱,很容易写出一个超时实际上并没有取消你以为它取消的东西。Python 3.11 新增的 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.timeout()</code> 是一个异步上下文管理器,它把截止时间变成<strong style="font-weight: border; color: rgb(248,57,41);">作用域的属性</strong>,而非某个具体调用的属性,因此可以干净地组合:外层超时可以包住整个 TaskGroup,组内每个任务还可以有自己更紧的嵌套超时。</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.timeout(overall_timeout):<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.TaskGroup() <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> tg:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">run_one</span><span class="hljs-params" style="line-height: 26px;">(name: str, conn)</span> -> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">None</span>:</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.timeout(per_backend_timeout):<br> results[name] = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> conn.query(user_id)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> (TimeoutError, Connection error) <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> e:<br> errors[name] = str(e)<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> name, conn <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> connections.items():<br> tg.create_task(run_one(name, conn))<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> TimeoutError:<br> errors[<span class="hljs-string" style="color: #98c379; line-height: 26px;">"_overall"</span>] = <span class="hljs-string" style="color: #98c379; line-height: 26px;">f"dashboard build exceeded <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{overall_timeout}</span>s overall budget"</span><br></code></pre>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">这里有两个层层嵌套的截止时间,含义不同。内层 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.timeout(per_backend_timeout)</code> 兜住某个慢后端,不影响其他后端——一次抖动调用不会拖垮整个请求。外层 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.timeout(overall_timeout)</code> 则对整个看板构建施加真实的总预算,触发时不管还有多少个后端在途都一刀切。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">我做过实测:故意把总预算设为 0.1 秒,而后端响应最长要 0.5 秒,结果是真正有用的行为而非硬崩溃——两个及时完成的快速后端进了结果,两个慢的被干净取消并记录为超时错误,整个请求约 0.16 秒就返回,而不是挂满 0.5 秒。硬截止下保住了部分结果,而且每一条连接——包括中途被取消的——都干净关闭,因为超时作用域位于第 3 节 AsyncExitStack <strong style="font-weight: border; color: rgb(248,57,41);">内部</strong>,而不是外面。</p>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">5. 内置任务内省工具,实时诊断编排问题</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">前四个技巧是预防问题。这一个用于生产里真出问题、而你需要<strong style="font-weight: border; color: rgb(248,57,41);">看见</strong>而不是猜测的时刻。Python 3.14 在此带来了一项全新能力:可以 attach 到正在运行的 Python 进程上,打印它的实时任务树,无需改代码、无需提前埋日志。</p>
<ul data-tool="mdnice编辑器" style="margin-top: 8px; margin-bottom: 8px; padding-left: 25px; color: black; list-style-type: disc; ;">
<li><section style="margin-top: 5px; margin-bottom: 5px; line-height: 26px; text-align: left; color: rgb(1,1,1); font-weight: 500; ;"><code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">ps</code> 给出进程中每个活跃任务的扁平表格:任务名、当前协程调用栈、当前在等待什么。</section></li><li><section style="margin-top: 5px; margin-bottom: 5px; line-height: 26px; text-align: left; color: rgb(1,1,1); font-weight: 500; ;"><code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">pstree</code> 用层级方式呈现同样信息,显示哪些任务由哪个 TaskGroup 派生——当一个看板聚合请求已经挂了两分钟,你想知道它到底是卡在风险模型后端,还是卡在你自己的编排代码里,这正是你想要的视图。</section></li></ul>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">在这之前,回答这个问题要么提前挂调试器,要么在代码里到处撒日志、再发一次版只为看个究竟。现在,它只是一条标准库命令、直接对已经在跑的进程执行。</p>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">专门提它,是因为它改变了前四个技巧的权衡:合理的超时和有界信号量减少了你需要它的次数,但当真正意外的挂死发生时,你仍然需要看一眼活进程;而从 3.14 开始,这是一条标准库命令的事,而不是一次调试会话。</p>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">完整可运行代码</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">三个文件,按所示原样测试,连接与信号量机制和编排逻辑分开,每一块单独都清晰可读。</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;"><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># backends.py</span><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> asyncio<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> random<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> dataclasses <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> dataclass<br><br>random.seed(<span class="hljs-number" style="color: #d19a66; line-height: 26px;">11</span>)<br><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@dataclass</span><br><span class="hljs-class" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">class</span> <span class="hljs-title" style="color: #e6c07b; line-height: 26px;">BackendStats</span>:</span><br> open_connections: int = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0</span><br> max_concurrent_open: int = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0</span><br> max_concurrent_in_flight: int = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0</span><br> in_flight: int = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0</span><br> total_calls: int = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0</span><br> total_failures: int = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0</span><br><br>STATS: dict[str, BackendStats] = {}<br><br>BACKEND_CONFIG = {<br> <span class="hljs-string" style="color: #98c379; line-height: 26px;">"pricing_api"</span>: {<span class="hljs-string" style="color: #98c379; line-height: 26px;">"latency"</span>: (<span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.02</span>, <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.05</span>), <span class="hljs-string" style="color: #98c379; line-height: 26px;">"capacity"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">20</span>, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"failure_rate"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.0</span>},<br> <span class="hljs-string" style="color: #98c379; line-height: 26px;">"positions_db"</span>: {<span class="hljs-string" style="color: #98c379; line-height: 26px;">"latency"</span>: (<span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.05</span>, <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.10</span>), <span class="hljs-string" style="color: #98c379; line-height: 26px;">"capacity"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">10</span>, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"failure_rate"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.0</span>},<br> <span class="hljs-string" style="color: #98c379; line-height: 26px;">"news_feed"</span>: {<span class="hljs-string" style="color: #98c379; line-height: 26px;">"latency"</span>: (<span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.15</span>, <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.25</span>), <span class="hljs-string" style="color: #98c379; line-height: 26px;">"capacity"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">5</span>, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"failure_rate"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.0</span>},<br> <span class="hljs-string" style="color: #98c379; line-height: 26px;">"risk_model"</span>: {<span class="hljs-string" style="color: #98c379; line-height: 26px;">"latency"</span>: (<span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.30</span>, <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.50</span>), <span class="hljs-string" style="color: #98c379; line-height: 26px;">"capacity"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">3</span>, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"failure_rate"</span>: <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.15</span>},<br>}<br><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> name <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> BACKEND_CONFIG:<br> STATS[name] = BackendStats()<br><br><span class="hljs-class" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">class</span> <span class="hljs-title" style="color: #e6c07b; line-height: 26px;">BackendConnection</span>:</span><br> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">__init__</span><span class="hljs-params" style="line-height: 26px;">(self, backend_name: str)</span>:</span><br> self.backend_name = backend_name<br> self._config = BACKEND_CONFIG[backend_name]<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">open</span><span class="hljs-params" style="line-height: 26px;">(self)</span> -> "BackendConnection":</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> asyncio.sleep(<span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.01</span>)<br> stats = STATS[self.backend_name]<br> stats.open_connections += <span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span><br> stats.max_concurrent_open = max(stats.max_concurrent_open, stats.open_connections)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> self<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">close</span><span class="hljs-params" style="line-height: 26px;">(self)</span> -> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">None</span>:</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> asyncio.sleep(<span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.005</span>)<br> STATS[self.backend_name].open_connections -= <span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span><br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">query</span><span class="hljs-params" style="line-height: 26px;">(self, request_id: str)</span> -> dict:</span><br> stats = STATS[self.backend_name]<br> stats.in_flight += <span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span><br> stats.max_concurrent_in_flight = max(stats.max_concurrent_in_flight, stats.in_flight)<br> stats.total_calls += <span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> low, high = self._config[<span class="hljs-string" style="color: #98c379; line-height: 26px;">"latency"</span>]<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> asyncio.sleep(random.uniform(low, high))<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">if</span> random.random() < self._config[<span class="hljs-string" style="color: #98c379; line-height: 26px;">"failure_rate"</span>]:<br> stats.total_failures += <span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">raise</span> Connection error(<span class="hljs-string" style="color: #98c379; line-height: 26px;">f"<span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.backend_name}</span> timed out for request <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{request_id}</span>"</span>)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> {<span class="hljs-string" style="color: #98c379; line-height: 26px;">"backend"</span>: self.backend_name, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"request_id"</span>: request_id, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"data"</span>: <span class="hljs-string" style="color: #98c379; line-height: 26px;">f"result-from-<span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.backend_name}</span>"</span>}<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">finally</span>:<br> stats.in_flight -= <span class="hljs-number" style="color: #d19a66; line-height: 26px;">1</span><br></code></pre>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;"><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># pool.py</span><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> asyncio<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> contextlib <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> asynccontextmanager<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> backends <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> BackendConnection, BACKEND_CONFIG<br><br>_semaphores: dict[str, asyncio.Semaphore] = {<br> name: asyncio.Semaphore(cfg[<span class="hljs-string" style="color: #98c379; line-height: 26px;">"capacity"</span>]) <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> name, cfg <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> BACKEND_CONFIG.items()<br>}<br><br><span class="hljs-me ta" style="color: #61aeee; line-height: 26px;">@asynccontextmanager</span><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">acquire_connection</span><span class="hljs-params" style="line-height: 26px;">(backend_name: str)</span>:</span><br> semaphore = _semaphores[backend_name]<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> semaphore:<br> conn = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> BackendConnection(backend_name).open()<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">yield</span> conn<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">finally</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> conn.close()<br></code></pre>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;"><span class="hljs-comment" style="color: #5c6370; font-style: italic; line-height: 26px;"># orchestrator.py</span><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> asyncio<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> contextlib <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> AsyncExitStack<br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">from</span> pool <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">import</span> acquire_connection<br><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">build_dashboard</span><span class="hljs-params" style="line-height: 26px;">(user_id: str, enabled_backends: list[str],<br> per_backend_timeout: float = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">0.6</span>,<br> overall_timeout: float = <span class="hljs-number" style="color: #d19a66; line-height: 26px;">1.0</span>)</span> -> dict:</span><br> results: dict[str, dict] = {}<br> errors: dict[str, str] = {}<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> AsyncExitStack() <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> stack:<br> connections = {<br> name: <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> stack.enter_async_context(acquire_connection(name))<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> name <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> enabled_backends<br> }<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.timeout(overall_timeout):<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.TaskGroup() <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> tg:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">run_one</span><span class="hljs-params" style="line-height: 26px;">(name: str, conn)</span> -> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">None</span>:</span><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">try</span>:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.timeout(per_backend_timeout):<br> results[name] = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> conn.query(user_id)<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> (TimeoutError, Connection error) <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> e:<br> errors[name] = str(e)<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> name, conn <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> connections.items():<br> tg.create_task(run_one(name, conn))<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">except</span> TimeoutError:<br> errors[<span class="hljs-string" style="color: #98c379; line-height: 26px;">"_overall"</span>] = <span class="hljs-string" style="color: #98c379; line-height: 26px;">f"dashboard build exceeded <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{overall_timeout}</span>s overall budget"</span><br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> {<span class="hljs-string" style="color: #98c379; line-height: 26px;">"user_id"</span>: user_id, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"results"</span>: results, <span class="hljs-string" style="color: #98c379; line-height: 26px;">"errors"</span>: errors}<br><br><br><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">build_dashboards_for_batch</span><span class="hljs-params" style="line-height: 26px;">(user_ids: list[str], enabled_backends: list[str])</span> -> list[dict]:</span><br> dashboards: list[dict] = []<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">with</span> asyncio.TaskGroup() <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">as</span> tg:<br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">async</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">run_one</span><span class="hljs-params" style="line-height: 26px;">(uid: str)</span> -> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">None</span>:</span><br> dashboard = <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">await</span> build_dashboard(uid, enabled_backends)<br> dashboards.append(dashboard)<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">for</span> uid <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">in</span> user_ids:<br> tg.create_task(run_one(uid))<br><br> <span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> dashboards<br></code></pre>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">如何运行</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">把上面三个文件放在同一目录,然后用 Python 3.11+ 解释器运行:</p>
<pre class="custom" data-tool="mdnice编辑器" style="margin-top: 10px; margin-bottom: 10px;"><code class="hljs" style="overflow-x: auto; padding: 16px; color: #abb2bf; background: #282c34; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; border-radius: 0px; ; -webkit-overflow-scrolling: touch;">python3 -c <span class="hljs-string" style="color: #98c379; line-height: 26px;">"<br>import asyncio<br>from orchestrator import build_dashboards_for_batch<br>from backends import BACKEND_CONFIG<br><br>async def main():<br> user_ids = [f'user_{i}' for i in range(30)]<br> dashboards = await build_dashboards_for_batch(user_ids, list(BACKEND_CONFIG.keys()))<br> print(f'Completed {len(dashboards)} dashboards')<br> errors = sum(len(d['errors']) for d in dashboards)<br> print(f'Total backend errors: {errors} (risk_model has a 15% simulated failure rate)')<br><br>asyncio.run(main())<br>"</span><br></code></pre>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">这就是写本文时同一次批量运行的结果:30 个并发用户、全部四个后端、每条连接都干净关闭零泄漏,与前面每一节验证的一致。想直接看第 4 节的超时行为,单独调用 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">build_dashboard("test_user", list(BACKEND_CONFIG.keys()), overall_timeout=0.1)</code>——这个预算对慢后端太紧、来不及完成——你会看到部分结果和 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">_overall</code> 超时错误一起返回,而不是调用一直挂着。</p>
<h2 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ; text-align: left; margin: 20px 10px 0px 0px;"><span class="prefix" style="display: none;"></span><span class="content" style="font-family: STHeitiSC-Light; ; font-weight: bolder; display: inline-block; padding-left: 10px; border-left: 5px solid rgb(248,57,41);">收尾总结</span><span class="suffix"></span></h2>
<p data-tool="mdnice编辑器" style="padding-top: 8px; padding-bottom: 8px; color: black; margin: 10px 10px; line-height: 1.75; letter-spacing: 0.2em; ; word-spacing: 0.1em;">这五个技巧,没有一个是为了让代码跑更快。TaskGroup 不会让任务跑得更快,它让失败模式可预测;Semaphore 不会加速任何东西,它防止快路径悄悄压垮较慢的依赖;AsyncExitStack 和 <code style="; word-wrap: break-word; padding: 2px 4px; border-radius: 4px; margin: 0 2px; background-color: rgba(27,31,35,.05); font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; word-break: break-all; color: rgb(271,93,108);">asyncio.timeout()</code> 完全是关于出错时怎么办、而不是顺利时怎么办;第 5 节的内省工具,则纯粹为"预防手段仍不够"的那一刻而存在。这就是资源编排作为一门技能的真实形态:并发几乎是白送的速度,但在真实失败下依然有界、无泄漏、可恢复的并发,才是必须刻意构建的部分。而从 Python 3.14 开始,标准库终于给了你一套真正完整的工具箱来构建它。</p>
<h3 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ;"><span class="prefix" style="display: none;"></span><span class="content" style="; color: rgb(165,213,93);">推荐学习书籍 《<strong style="font-weight: border; color: rgb(248,57,41);">CDA一级教材</strong>》适合CDA一级考生备考,也适合业务及数据分析岗位的从业者提升自我。完整电子版已上线CDA网校,累计已有10万+在读~ !</span><span class="suffix" style="display: none;"></span></h3>
<figure data-tool="mdnice编辑器" style="margin: 0; margin-top: 10px; margin-bottom: 10px; display: flex; flex-direction: column; justify-content: center; align-items: center;"><img src="https://file.haoxueai.cn/haoxue/img/4502d41c-fb3a-43a8-bf50-9e14aedde094.png" alt style="max-width: 100%; border-radius: 0px 0px 5px 5px; display: block; margin: 20px auto; width: 85%; height: 100%; ob ject-fit: contain; box-shadow: #84A1A8 0px 10px 15px;"></figure>
<h3 data-tool="mdnice编辑器" style="margin-top: 30px; margin-bottom: 15px; padding: 0px; font-weight: bold; color: black; ;"><span class="prefix" style="display: none;"></span><span class="content" style="; color: rgb(165,213,93);">免费加入阅读:<a href="https://edu.cda.cn/goods/show/3151?targetId=5147&preview=0" style="text-decoration: none; word-wrap: break-word; font-weight: bold; color: rgb(248,57,41); border-bottom: 1px solid #ff3502; font-family: STHeitiSC-Light;">https://edu.cda.cn/goods/show/3151?targetId=5147&preview=0</a></span><span class="suffix" style="display: none;"></span></h3>
</section>