Python Dash:回调执行过程中同步实时更新页面元素的实现问题
Dash回调执行中实时更新中间进度的实现方案
普通同步回调无法满足中途更新UI的需求,因为回调函数执行完成后才会批量返回所有输出值,你需要使用Dash的**长回调(Long Callback)**机制实现进度实时更新,修改后可直接运行的完整代码如下:
import pandas as pd import diskcache from dash import Dash, long_callback, Input, Output, html # 配置长回调本地缓存后端,无需额外部署服务 cache = diskcache.Cache("./dash_temp_cache") app = Dash(__name__) app.config["LONG_CALLBACK_RUNNER"] = { "backend": "diskcache", "cache": cache } app.layout = html.Div( [ html.Button("execute callback", id="button"), html.Div(children="live updated of progress", id="update-output"), html.Div(children="wait for final output", id="final-output"), ] ) @long_callback( Output("final-output", "children"), Input("button", "n_clicks"), # 绑定进度更新的目标组件 progress=[Output("update-output", "children")], prevent_initial_call=True ) def change_text(set_progress, n_clicks): # 第一步完成后更新进度 df1 = pd.DataFrame([[1, 2, 3],[2, 3, 4]], columns=['a', 'b', 'c']) s = 'df1 done' set_progress(s) # 第二步完成后更新进度 df2 = pd.DataFrame([[1, 2, 3],[2, 3, 4]], columns=['a', 'b', 'c']) s = 'df2 done' set_progress(s) # 第三步完成后更新进度 df3 = pd.DataFrame([[1, 2, 3],[2, 3, 4]], columns=['a', 'b', 'c']) s = 'df3 done' set_progress(s) # 全部完成后返回最终结果 df = pd.concat([df1, df2, df3]) return str(df.to_dict('records')) if __name__ == '__main__': app.run_server(debug=True)
运行说明
- 先安装依赖:
pip install dash diskcache pandas - 如果你使用的是2.0以下版本的Dash,先执行升级:
pip install --upgrade dash - 启动服务后点击按钮,即可看到
update-output组件逐行更新进度,全部逻辑执行完成后final-output会显示最终拼接的DataFrame结果
实现关键点
- 长回调会将任务放到后台队列异步执行,不会阻塞主服务
- 调用
set_progress方法时会立刻将值更新到绑定的进度组件,不会中断后续逻辑运行 - 本地测试/小流量场景用diskcache作为后端即可,生产环境可替换为Celery+Redis/RabbitMQ的组合支撑高并发
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

