【问题标题】:Using python and flask, how can I pass a dynamic route argument to a new route called by the AJAX request?使用 python 和烧瓶,如何将动态路由参数传递给 AJAX 请求调用的新路由?
【发布时间】: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) }},它将在函数之间传递变量。但我想我也误解了

标签: python jquery ajax flask


【解决方案1】:

您可以将团队缩写存储为 HTML5 data 属性,并将缩写作为 ajax data 值的一部分传回:

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, abbrev=team_abbr)   

spending-performance-team.html 中,将abbrev 值呈现为每个按钮的data 属性:

<span class="graph-options" id="atl_wins_graph">
   <button class="atl_wins_graph left selected" value="No Seasons" data-abbr="{{abbrev}}">No Seasons</button>
   <button class="atl_wins_graph right" value="Seasons" data-abbr="{{abbrev}}">Seasons</button>
</span>

现在,在plots.js 中,更新ajax 请求的data 键:

$.ajax({
    url: "/spending-wins/",
    type: "GET",
    contentType: 'application/json;charset=UTF-8',
    data: { 'selected': this.value, 'abbr':$(this).data('abbr')},
    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=request.args.get('abbr')).order_by(NBAWinsvsSalary.season).all()
  graphJSON = wins_plot(team_query, feature, team_color, team_colors)
  return graphJSON

【讨论】:

  • 这非常有效!非常感谢您的回答。
  • 对任何使用这个问题的人来说,只是一个小小的说明。在额外的路线中,我不得不移除“烧瓶”。来自'team_abbr=flask.request.arg.get('abbr'))。这是因为我已经从 views.py 文件顶部的烧瓶中导入了请求。我忘了在我的问题中包含这个。
  • @DustinWest 很高兴为您提供帮助!将从答案中删除模块名称对象
【解决方案2】:

sports/nba/spending-performance-team.html 中创建一个值为team_abbr 的隐藏输入,就像win_graphnba_spending_performance_team 控制器中一样传递。然后让 JS 获取该值(类似于 $("#team-abbr").value)并将其作为 ajax 中的参数传递,然后就像选中一样,您有团队缩写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多