如何在Flask开发的Web应用中展示Retentioneering可交互用户行为分析图谱
实现方案
你无需从零重写全部交互逻辑,Retentioneering的可交互图谱底层基于Plotly生成,可直接导出为带交互能力的HTML片段嵌入Flask应用,核心实现步骤如下:
步骤1:Python侧导出可交互图谱HTML
你现有生成图谱的逻辑无需大改,仅需在调用绘图方法时关闭本地弹窗,再将图谱对象导出为HTML字符串即可保留全部交互能力:
import retentioneering import plotly.io as pio from retentioneering.datasets import load_simple_shop # 替换为你自己的业务分析逻辑 data = load_simple_shop() rete = retentioneering.ReteNet(data) # 加show=False不弹出本地预览窗口 graph_obj = rete.plot_graph(show=False, threshold=0.01) # 导出为HTML片段,保留拖拽节点、缩放、悬停查看数据等全部交互 graph_html = pio.to_html(graph_obj, full_html=False, include_plotlyjs='cdn')
步骤2:配置Flask路由与动态参数
你可以在路由中接收前端筛选控件的参数,动态生成不同条件下的图谱,实现和原生库一致的筛选效果:
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/behavior-graph') def show_behavior_graph(): # 接收前端传入的筛选参数,可根据需求扩展下拉选择、时间范围等更多参数 threshold = request.args.get('threshold', 0.01, type=float) event_type = request.args.get('event_type', 'all', type=str) # 带入筛选参数动态生成图谱 rete = retentioneering.ReteNet(data) graph_obj = rete.plot_graph(show=False, threshold=threshold, event_filter=event_type) graph_html = pio.to_html(graph_obj, full_html=False, include_plotlyjs='cdn') return render_template('graph.html', graph_html=graph_html, current_threshold=threshold, current_event=event_type) if __name__ == '__main__': app.run(debug=True)
步骤3:编写前端模板
不需要特殊的自定义组件,普通div即可承载可交互图谱,你只需要在模板中对应位置加和Retentioneering原生功能对齐的筛选控件即可:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>用户行为路径分析</title> <style> .controls { margin: 20px 0; } .graph-container { width: 100%; height: 800px; } </style> </head> <body> <!-- 筛选控件区,可根据需求扩展更多下拉、多选、输入框控件 --> <div class="controls"> <form method="get"> <label>节点阈值:</label> <input type="number" step="0.001" name="threshold" value="{{ current_threshold }}"> <label>事件类型:</label> <select name="event_type"> <option value="all" {% if current_event == 'all' %}selected{% endif %}>全部事件</option> <option value="page_view" {% if current_event == 'page_view' %}selected{% endif %}>页面访问</option> <option value="purchase" {% if current_event == 'purchase' %}selected{% endif %}>购买</option> </select> <button type="submit">更新图谱</button> </form> </div> <!-- 可交互图谱承载区 --> <div class="graph-container"> {{ graph_html|safe }} </div> </body> </html>
注意事项
- 拖拽节点、缩放、悬停查看数值等原生交互已经包含在导出的Plotly HTML片段中,不需要额外开发
- 如果需要无刷新更新图谱,可给表单加AJAX提交逻辑,后端返回新的graph_html片段替换容器内容即可
- 如果访问环境无法连接公共CDN,可将Plotly.js下载到本地静态资源目录,导出时将
include_plotlyjs参数改为本地资源路径即可
内容的提问来源于stack exchange,提问作者frustani
相关产品推荐
相关产品推荐

