在Flask应用中如何获取Bokeh用户交互数据并同步至服务端?
如何将Bokeh Point Draw Tool的用户数据同步回Flask后端
当然可以!你完全能把用户通过Point Draw Tool创建、拖拽或删除的点数据同步回Flask服务端。下面是具体的实现思路、步骤和修改后的代码:
实现核心思路
我们需要通过三个关键环节完成数据同步:
- 前端监听Bokeh数据源的变化事件
- 用AJAX将更新后的数据发送到Flask后端路由
- 后端接收数据并进行后续处理(存储、计算等)
修改后的webapp.py
from flask import Flask, render_template, request, jsonify from bokeh.plotting import figure, ColumnDataSource, Column from bokeh.models import DataTable, TableColumn, PointDrawTool from bokeh.embed import components from bokeh.resources import INLINE app = Flask(__name__) @app.route("/") def show_data(): p = figure(x_range=(0, 10), y_range=(0, 10), tools=[], title='Point Draw Tool') p.background_fill_color = 'lightgrey' source = ColumnDataSource({ 'x': [1, 5, 9], 'y': [1, 5, 9], 'color': ['red', 'green', 'yellow'] }) renderer = p.scatter(x='x', y='y', source=source, color='color', size=10) columns = [TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field='color', title='color')] table = DataTable(source=source, columns=columns, editable=True, height=200) draw_tool = PointDrawTool(renderers=[renderer], empty_value='black') p.add_tools(draw_tool) p.toolbar.active_tap = draw_tool script, div = components(Column(p,table)) return render_template('index.html', script=script, div=div, js_resources=INLINE.render_js(), css_resources=INLINE.render_css()) # 新增接收前端数据的路由 @app.route('/update-data', methods=['POST']) def update_data(): # 获取前端发送的JSON格式数据 data = request.get_json() # 这里可以添加你的自定义处理逻辑:比如存储到数据库、打印验证、数据分析等 print("收到用户更新的数据:", data) # 返回成功响应给前端 return jsonify({"status": "success", "message": "数据已成功接收"}) if __name__ == '__main__': app.run(port=5000, debug=True)
修改后的index.html
<!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>User Interaction</title> {{ js_resources|safe }} {{ css_resources|safe }} {{ script|safe }} </head> <body> {% block body %} {{ div|safe }} {% endblock %} <script> // 获取Bokeh文档中的ColumnDataSource实例 const source = Bokeh.documents[0].get_model_by_name('{{ source.name }}'); // 监听数据源的变化事件 source.on('change', () => { // 延迟100ms发送请求,避免拖拽过程中频繁触发请求,确保拿到最终数据 setTimeout(() => { // 提取当前数据源的完整数据 const updatedData = source.data; // 发送POST请求到Flask后端 fetch('/update-data', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(updatedData), }) .then(response => response.json()) .then(result => { console.log('数据同步成功:', result); }) .catch(error => { console.error('数据同步失败:', error); }); }, 100); }); </script> </body> </html>
关键细节说明
- 数据源实例获取:通过
Bokeh.documents[0].get_model_by_name获取对应的数据源,source.name是Bokeh自动生成的唯一标识,直接在模板中引用即可。 - 延迟请求:添加
setTimeout是因为拖拽点的过程中,数据源会连续触发多次变化事件,延迟可以确保我们获取到最终的更新结果。 - 后端扩展:在
/update-data路由中,你可以根据需求替换print语句,比如将数据写入SQLite/MySQL数据库,或者进行实时计算分析。 - 调试验证:启动Flask应用后,操作页面上的点,后端控制台会打印收到的数据,以此验证同步是否成功。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

