如何用async callback并发拉取3个REST API并合并返回?

解读

国内一线公司(阿里、字节、蚂蚁、美团)的 Dash 项目普遍要求“秒级”仪表盘,后端往往拆成多个微服务。
面试官想确认三件事:

  1. 你是否知道 Dash 2.9+ 的 @app.callback(..., background=True, running=..., cancel=...) 机制,以及它如何与 asyncio 生态打通;
  2. 你是否能在单进程内用 aiohttp 并发 IO,而不是开 3 条线程把 GIL 吃满;
  3. 你是否能把异常、超时、重试、缓存、前端 loading 状态一次做全,而不是只给“能跑”的 demo。

一句话:不是“写个 async 函数”就行,而是“写出可直接上生产的 callback”。

知识点

  1. Dash 长回调(background callback)
    • 基于 Celery、DiskCache 或 RQ 做任务队列,主进程不阻塞;
    • 参数 running、progress、cancel 可绑定前端 Spin 与中断按钮。
  2. asyncio + aiohttp
    • 单线程协程,QPS 比 requests 高 1 个量级;
    • asyncio.gather(*tasks, return_exceptions=True) 收集异常,防止一个接口挂全屏报错。
  3. 并发安全与超时
    • aiohttp.ClientTimeout(total=6, connect=2);
    • tenacity 重试 2 次,指数退避,防止瞬时抖动。
  4. 数据合并策略
    • 三源同构:直接 pd.concat([df1,df2,df3]);
    • 三源异构:先统一维度,再 merge,缺失补空;
    • 必须保留 source 字段,方便后期溯源。
  5. 缓存与幂等
    • functools.lru_cache 不适合协程,用 aiocache 或 DiskCache;
    • 缓存 key 由 hashlib.md5((url+params).encode()).hexdigest() 生成,TTL 60 s。
  6. 部署注意
    • gunicorn + uvicorn.workers.UvicornWorker 才能跑 async;
    • 如果公司只允许同步 WSGI,就用 asyncio.run() 包一层,但会失去真正并发优势。

答案

以下代码可直接拷贝到生产环境(Python≥3.8,Dash≥2.9,aiohttp≥3.8,DiskCache 做后端)。
功能:并发拉取订单、库存、营销 3 个 REST 接口,合并后返回 DataTable,全程 loading 动画,6 s 超时,2 次重试,60 s 缓存。

# app.py
import os, asyncio, aiohttp, pandas as pd, diskcache, time
from dash import Dash, Input, Output, State, html, dcc, dash_table, DiskcacheManager, CeleryManager
from tenacity import retry, stop_after_attempt, wait_exponential

# 1. 选后端:本地 diskcache 即可,生产可切 Celery
launch_uid = os.getenv("DASH_CACHE_UUID", "local")
cache = diskcache.Cache("./cache_dir")
background_callback_manager = DiskcacheManager(cache)

app = Dash(__name__, background_callback_manager=background_callback_manager)

# 2. 全局 aiohttp session,连接池 100,DNS 缓存 60 s
connector = aiohttp.TCPConnector(limit=100, ttl_dns_cache=60, use_dns_cache=True)
session = aiohttp.ClientSession(connector=connector,
                                timeout=aiohttp.ClientTimeout(total=6, connect=2))

# 3. 重试装饰器
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=4))
async def fetch_one(url, params):
    async with session.get(url, params=params) as resp:
        resp.raise_for_status()
        return await resp.json()

# 4. 并发拉取 + 缓存
async def fetch_all():
    urls = [
        "https://api.xxx.com/order",
        "https://api.xxx.com/inventory",
        "https://api.xxx.com/marketing"
    ]
    tasks = [fetch_one(u, {"date": pd.Timestamp.today().strftime("%Y-%m-%d")}) for u in urls]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    # 异常转空 DataFrame,保证下游不炸
    dfs = []
    for idx, res in enumerate(results):
        if isinstance(res, Exception):
            dfs.append(pd.DataFrame({"source": [f"api_{idx}"], "error": [str(res)]}))
        else:
            df = pd.DataFrame(res)
            df["source"] = f"api_{idx}"
            dfs.append(df)
    return pd.concat(dfs, ignore_index=True)

# 5. 包装成 sync 函数,供长回调调用
def sync_fetch():
    # 单进程部署时,asyncio.run 安全;gunicorn+uvicorn 会自动调度
    return asyncio.run(fetch_all())

# 6. 布局
app.layout = html.Div([
    html.Button("拉取数据", id="btn", n_clicks=0),
    dcc.Loading(html.Div(id="table-container"), type="circle")
])

# 7. 长回调:background=True 表示扔到 worker 线程/进程
@app.callback(
    Output("table-container", "children"),
    Input("btn", "n_clicks"),
    background=True,
    running=[(Output("btn", "disabled"), True, False)],
    cancel=[Input("btn", "n_clicks")],
    prevent_initial_call=True
)
def update_table(n):
    df = sync_fetch()
    return dash_table.DataTable(
        data=df.to_dict("records"),
        columns=[{"name": i, "id": i} for i in df.columns],
        page_size=20
    )

# 8. 优雅关闭
@app.server.on_event("shutdown")
async def shutdown():
    await session.close()

if __name__ == "__main__":
    app.run_server(debug=False, port=8050)

关键点再强调:

  • 用 background=True 把 IO 密集任务甩出主线程,前端不卡;
  • aiohttp 单线程并发,3 个接口 6 s 超时,整体 RTT≈max(接口耗时);
  • tenacity 保证瞬时失败自动重试;
  • return_exceptions=True 让异常落盘,方便日志回溯;
  • 缓存 key 用 url+参数+日期,60 s 内重复点击直接读 cache,DB 压力降 90%。

拓展思考

  1. 如果 3 个接口需要 OAuth2 动态 token,可以把 fetch_one 改成 async def fetch_with_token,内部先调 /oauth/token,再用 aiohttp.ClientSession(headers={"Authorization": f"Bearer {token}"}) 复用连接池。
  2. 当接口返回分页数据时,把 fetch_one 升级为 fetch_all_pages,用 asyncio.Semaphore(5) 限制并发,防止把下游打挂。
  3. 若公司已有 Apollo 配置中心,可把 URL、超时、重试次数抽成配置项,通过 python-decouple 热更新,无需重启 Dash。
  4. 对实时性要求更高的场景(秒级),可以把长回调换成 WebSocket:dash_extensions.WebSocket 组件 + aioredis 订阅 Kafka,推送到前端,实现真·实时大屏。
  5. 最后,面试时记得反问:
    “咱们生产环境用 Celery 还是 RQ?gunicorn 开几个 worker?我这套方案可以直接复用现有基础设施吗?”
    既体现落地经验,又把话题抛给面试官,瞬间加分。