如何通过Flask路由+iframe加载Dash仪表盘并显示图表?
问题解决:将Dash仪表盘嵌入Flask的iframe中
问题根源
你的代码存在两个核心问题:
- Flask的
/app1路由返回包含iframe的页面,而iframe又请求/app1,形成无限循环,无法加载实际的Dash内容 - Dash应用未与Flask主应用集成,只是简单导入,没有挂载到Flask的路由体系中
修正步骤
1. 修改Dash应用文件(app1.py、app2.py)
将Dash应用改为可被Flask主应用挂载的形式,指定路由前缀:
app1.py
import dash from dash import html, dcc def create_dash_app(server): # 关联Flask主应用,设置Dash的路由前缀 app = dash.Dash( __name__, server=server, requests_pathname_prefix='/app1/dash/' ) app.layout = html.Div( children=[ html.H1('App 1'), dcc.Graph( id='graph1', figure={ 'data': [{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'App 1'}], 'layout': {'title': 'App 1 Graph'} } ) ] ) return app
app2.py
import dash from dash import html, dcc def create_dash_app(server): app = dash.Dash( __name__, server=server, requests_pathname_prefix='/app2/dash/' ) app.layout = html.Div( children=[ html.H1('App 2'), dcc.Graph( id='graph2', figure={ 'data': [{'x': [1, 2, 3], 'y': [2, 4, 1], 'type': 'bar', 'name': 'App 2'}], 'layout': {'title': 'App 2 Graph'} } ) ] ) return app
2. 修改Flask主应用(main.py)
导入并挂载Dash应用到Flask主服务:
from flask import Flask, render_template from app1 import create_dash_app as create_app1 from app2 import create_dash_app as create_app2 app = Flask(__name__) # 将两个Dash应用挂载到Flask主应用 create_app1(app) create_app2(app) @app.route('/') def index(): return 'Main App' @app.route('/app1') def render_dashboard1(): return render_template('dashboard1.html') @app.route('/app2') def render_dashboard2(): return render_template('dashboard2.html') if __name__ == '__main__': app.run(debug=True)
3. 修改HTML模板文件(dashboard1.html、dashboard2.html)
将iframe的src指向Dash应用的实际路由前缀:
dashboard1.html
<!-- dashboard1.html --> <!DOCTYPE html> <html> <head> <title>Dashboard 1</title> </head> <body> <h1>Dashboard 1</h1> <iframe src="/app1/dash" width="1000" height="800" frameborder="0"></iframe> </body> </html>
dashboard2.html
<!-- dashboard2.html --> <!DOCTYPE html> <html> <head> <title>Dashboard 2</title> </head> <body> <h1>Dashboard 2</h1> <iframe src="/app2/dash" width="1000" height="800" frameborder="0"></iframe> </body> </html>
验证运行
启动main.py后:
- 访问
http://localhost:5000/app1,即可看到嵌入了App1仪表盘的页面 - 访问
http://localhost:5000/app2,即可看到嵌入了App2仪表盘的页面
内容的提问来源于stack exchange,提问作者onhalu
相关产品推荐
相关产品推荐

