基于Python Flask的用户输入驱动Plotly图表网页展示问题排查
基于Flask+Plotly实现动态图表的问题与解决
需求与实现代码
目标是通过Python Flask,结合用户输入在浏览器中展示Plotly动态图表,最初使用python -m http.server启动服务器。
Flask后端代码(app.py)
from flask import Flask, render_template, request from flask_cors import CORS, cross_origin import pandas as pd import json import plotly import plotly.express as px app = Flask(__name__) CORS(app) @cross_origin() @app.route('/callback', methods=['POST', 'GET']) def cb(): return gm(request.args.get('data')) @app.route('/') def index(): return render_template('localhost:8000/chartsajax.html', graphJSON=gm()) def gm(country='United Kingdom'): df = pd.DataFrame(px.data.gapminder()) fig = px.line(df[df['country']==country], x="year", y="gdpPercap") graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON if __name__ == '__main__': app.run(host='localhost', port=8000, debug=False)
前端HTML代码(chartsajax.html)
<!doctype html> <html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function cb(selection) { $.getJSON({ url: "/callback", data: { 'data': selection }, success: function (result) { Plotly.react('chart', result, {});; } }); } </script> </head> <body style="font-family:arial, sans-serif"> <h1>GDP per Capita Over Time</h1> <h2>Choose your country</h2> <p>Make sure you spell it correctly with capital letter(s), e.g. United Kingdom</p> <input type="text" id="fname" name="fname" onchange="cb(this.value)"> <div id="chart" class="chart"></div> <div id="png_chart"></div> </body> <script> cb("United Kingdom"); </script> </html>
遇到的问题
- 启动服务器后,访问
localhost:8000/chartsajax.html时功能正常,但访问http://localhost:8000/chartsajax.html时,仅能显示输入框,出现304错误;输入“United Kingdom”后触发404错误。 - 排查方向锁定为目录结构或
request.args.get('data'),尝试多种代码调整仍无法正常显示图表。
解决过程
- 尝试按规范在
app.py同级目录添加templates文件夹后,访问本地路径出现错误,这也是最初选择使用Python HTTP Server的原因。 - 最终直接访问
localhost:8000(即Flask的根路由),所有功能正常运行,问题解决。
内容的提问来源于stack exchange,提问作者someds
相关产品推荐
相关产品推荐

