基于Flask部署Bokeh/Panel服务后前端无法渲染可视化内容如何解决
问题修复方案
你的问题核心是server_document的URL参数缺少HTTP协议头,导致浏览器将Panel服务地址识别为Flask服务下的相对路径,资源请求失败。按以下步骤修改即可:
1. 修正Flask路由中的server_document配置
修改main_test.py里的index路由,给url参数补全http://协议头:
@app.route('/') def index(): # 补全http协议头,本地测试用http://localhost:5006,生产环境替换为实际部署地址 script = server_document(url='http://localhost:5006') print("Session Pulled!", datetime.now()) print(script) return render_template("embed.html", script=script)
2. 优化embed.html模板(可选,避免无效变量报错)
你当前模板中使用的resources和div变量没有从Flask路由传入,server_document返回的script标签会自动加载所需资源并渲染图表,可直接简化模板为:
<head></head> {% block content %} <h1>Plot should be here.</h1> <div> {{ script|safe }} </div> {% endblock %}
3. 通用排查步骤(如修改后仍未生效)
打开浏览器开发者工具(F12),切换到「控制台」和「网络」标签页排查错误:
- 若出现404错误:确认Panel服务正常运行,地址、端口与配置一致
- 若出现CORS跨域错误:检查
panel_test.py中allow_websocket_origin列表已添加当前Flask服务的地址(含端口) - 若出现WebSocket连接失败:生产环境使用HTTPS的情况下,需要将Panel服务的访问地址改为
https://开头,同时确保WebSocket协议对应为wss://
你当前panel_test.py中的跨域配置是正确的,无需额外修改。
内容的提问来源于stack exchange,提问作者A Barra
相关产品推荐
相关产品推荐

