【发布时间】:2019-01-22 22:31:50
【问题描述】:
我在我的 Python Flask 应用程序中创建了一个动态路由来显示一个动态 html 模板。在页面的顶部,每个页面都有一个不同的图表(wins_graph 变量)。每个页面最初都按应有的方式显示。
views.py(初始路线)
@app.route('/sports/nba/<team_abbr>-spending-performance/')
def nba_spending_performance_team(team_abbr):
team_query = NBAWinsvsSalary.query.filter_by(team_abbr=team_abbr).order_by(NBAWinsvsSalary.season).all()
team_colors = 'RdBu'
wins_graph = Functions.wins_plot(team_query, 'No Seasons', 'rgba(175, 27, 50, 1)', team_colors)
return render_template('sports/nba/spending-performance-team.html', wins_graph)
sports/nba/spending-performance-team.html
<header>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
</header>
<body>
<div class="graph-container">
<div class="graph-options">
<label> Choose the plot type....</label>
<span class="graph-options" id="atl_wins_graph">
<button class="atl_wins_graph left selected" value="No Seasons">No Seasons</button>
<button class="atl_wins_graph right" value="Seasons">Seasons</button>
</span>
</div>
<div class="graph" id="wins_graph">
<script>
var graphs = {{wins_graph | safe}};
Plotly.plot('wins_graph',graphs,{});
</script>
</div>
</div>
<script src="{{ url_for('static', filename='js/jquery-3.3.1.js') }}"></script>
<script src="{{ url_for('static', filename='js/plots.js') }}"></script>
</body>
如您所见,图表上方有两个按钮。我想显示第二个图表,但仅在单击第二个按钮时。我已经编写了一个 AJAX 调用来处理这个问题。
plots.js
$('.atl_wins_graph').on('click',function(){
$('#selected').html(this.value);
$('.atl_wins_graph').removeClass('selected');
$(this).addClass('selected');
$.ajax({
url: "/spending-wins/",
type: "GET",
contentType: 'application/json;charset=UTF-8',
data: { 'selected': this.value },
dataType:"json",
success: function (data) {
Plotly.newPlot('wins_graph', data );
}
});
});
还有一条与新图对应的附加路线。
views.py(附加路线)
@app.route('/spending-wins/', methods=['GET', 'POST'])
def spending_change_wins():
feature = request.args['selected']
team_color = 'rgba(175, 27, 50, 1)'
team_colors = 'RdBu'
team_query = NBAWinsvsSalary.query.filter_by(team_abbr=team_abbr).order_by(NBAWinsvsSalary.season).all()
graphJSON = wins_plot(team_query, feature, team_color, team_colors)
return graphJSON
问题在于附加路由中的 team_query 变量,因为我没有定义 team_abbr。
我收到的错误是:
NameError: name 'team_abbr' is not defined
我明白为什么会出现此错误。如果我用数据库中的实际值定义 team_abbr,那么一切都会按应有的方式进行。但这不是一个合理的解决方案,因为现在路线不是动态的。
我只是不知道如何将 team_abbr 参数从初始路由传递到附加路由,而无需使用重定向。任何帮助将不胜感激。
【问题讨论】:
-
如果您使用
{{ url_for(something, team_abbr=team_abbr) }},它将在函数之间传递变量。但我想我也误解了