烧瓶将request.form值传递给url_for

时间:2018-09-20 15:59:36

标签: python html forms flask

我有一个Flask模板,它显示一个页面,其中包含dropdown的{​​{1}}列表,具有所有者的输赢记录的owners和要切换的tableradio季节记录和regular记录之间。

所需的工作流程是:

  1. 如果通过导航栏导航到该页面,则默认应为playoff。 (有效)
  2. 否则,每当切换/matchup-history/regular时,它都应进行相应的路由。 (这不起作用)

matchup-history.html

radio

matchup-history / regular.html

{%- extends "base.html" -%}
{% block nav_matchups %}active{% endblock %}
{%- block content -%}
  <form action="{{ url_for('show_matchup_history', matchup_type=request.form['matchup_type']) }}" method="post">
    <label>
      <select name="owner_id" onchange="this.form.submit()">
      {%- for o in owners %}
        {%- if request.form['owner_id'] == o['owner_id']|string() %}
        <option value="{{ o['owner_id'] }}" selected>{{o['first_name'] + " " + o['last_name'] }}</option>
        {%- else %}
        <option value="{{ o['owner_id'] }}">{{o['first_name'] + " " + o['last_name'] }}</option>
        {%- endif %}
      {%- endfor %}
      </select>
    </label>
    {% block matchup_type_radio %}{% endblock %}
  </form>
  {%- if records|length > 0 %}
  <div class="stats-table">
    <table>
      <tr>
        {%- for th in table_headers %}
        <th>{{ th }}</th>
        {%- endfor %}
      </tr>
      {%- for r in records %}
      <tr>
        {%- for cn in column_names %}
        <td>{{ r[cn] }}</td>
        {%- endfor %}
      </tr>
      {%- endfor %}
    </table>
  </div>
  {%- endif %}
{% endblock -%}

matchup-history / playoffs.html

{%- extends "matchup-history.html" -%}
{% block matchup_type_radio %}
<label><input type="radio" name="matchup_type" value="regular" onclick="this.form.submit()" checked>Regular Season</label>
<label><input type="radio" name="matchup_type" value="playoffs" onclick="this.form.submit()">Playoffs</label>
{% endblock %}

app.py

{%- extends "matchup-history.html" -%}
{% block matchup_type_radio %}
<label><input type="radio" name="matchup_type" value="regular" onclick="this.form.submit()">Regular Season</label>
<label><input type="radio" name="matchup_type" value="playoffs" onclick="this.form.submit()" checked>Playoffs</label>
{% endblock %}

页面在点击时正确加载@app.route('/matchup-history/<string:matchup_type>', methods=['GET', 'POST']) def show_matchup_history(matchup_type): table_headers = ["Opponent", "Wins", "Losses"] column_names = ["opponent_owner_name", "wins", "losses"] owners = queries.get_owners() if request.method == 'POST': owner_id = request.form['owner_id'] else: owner_id = owners[0]['owner_id'] if matchup_type == REGULAR_SEASON: records = queries.get_matchup_history_regular(owner_id) else: records = queries.get_matchup_history_playoffs(owner_id) return render_template("matchup-history/{matchup_type}.html".format(matchup_type=matchup_type), title='Matchup History', table_headers=table_headers, column_names=column_names, owners=owners, records=records) ,但是只要切换单选按钮,页面就会失败:

/matchup-history/regular

呈现127.0.0.1 - - [20/Sep/2018 08:32:53] "GET /matchup-history/regular HTTP/1.1" 200 - 127.0.0.1 - - [20/Sep/2018 08:32:56] "POST /matchup-history/ HTTP/1.1" 404 - request.form['matchup_type']似乎是空的,因此提交表单将不会达到预期的效果。如何重构将matchup-history.html路由到其他url_for

编辑:根据@Joost的建议,我重新考虑了设计。

matchup-history.html

matchup_type

base.html

{%- extends "base.html" -%}
{% block nav_matchups %}active{% endblock %}
{%- block content -%}
  <form action="{{ url_for('show_matchup_history') }}" method="get">
    <label>
      <select name="owner_id" onchange="this.form.submit()">
      {%- for o in owners %}
        <option value="{{ o['owner_id'] }}" {%- if o['owner_id'] == selected_owner %} selected {% endif %}>{{o['first_name'] + " " + o['last_name'] }}</option>
      {%- endfor %}
      </select>
    </label>
    <label><input type="radio" name="matchup_type" value="regular" onclick="this.form.submit()" {%- if matchup_type == "regular" %} checked {% endif %}>Regular Season</label>
    <label><input type="radio" name="matchup_type" value="playoffs" onclick="this.form.submit()"{%- if matchup_type == "playoffs" %} checked {% endif %}>Playoffs</label>
  </form>
  {%- if records|length > 0 %}
  <div class="stats-table">
    <table>
      <tr>
        {%- for th in table_headers %}
        <th>{{ th }}</th>
        {%- endfor %}
      </tr>
      {%- for r in records %}
      <tr>
        {%- for cn in column_names %}
        <td>{{ r[cn] }}</td>
        {%- endfor %}
      </tr>
      {%- endfor %}
    </table>
  </div>
  {%- endif %}
{% endblock -%}

app.py

...
<a href="{{ url_for('show_matchup_history') }}" class="{% block nav_matchups %}{% endblock %}">Matchups</a>
...

流量现在为:

  1. 从导航栏中单击@app.route('/matchup-history', methods=['GET']) def show_matchup_history(): table_headers = ["Opponent", "Wins", "Losses"] column_names = ["opponent_owner_name", "wins", "losses"] matchup_type = request.args.get('matchup_type', default="regular") owner_id = request.args.get('owner_id', type=int) owners = queries.get_owners() if not owner_id: owner_id = owners[0]['owner_id'] if matchup_type == REGULAR_SEASON: records = queries.get_matchup_history_regular(owner_id) else: records = queries.get_matchup_history_playoffs(owner_id) return render_template("matchup-history.html".format(matchup_type=matchup_type), title='Matchup History', table_headers=table_headers, column_names=column_names, matchup_type=matchup_type, selected_owner=owner_id, owners=owners, records=records) 会转到Matchups,并且默认显示常规赛季的比赛。
  2. 点击/matchup-history广播将路由到Playoffs
  3. 点击/matchup-history?matchup_type=playoffs&owner_id=12345广播将路由到Regular
  4. /matchup-history?matchup_type=regular&owner_id=12345中单击其他所有者将路由到dropdown

1 个答案:

答案 0 :(得分:0)

因此,您现在正尝试在get请求中访问request.form。但是,form在get请求中始终为空,因为那是get请求的本质。因此,只有当您通过发布请求访问路线@app.route('/matchup-history/<string:matchup_type>'时,它才能以正确的方式重定向。

这个可运行的miniapp很好地显示了它:

from flask import Flask, render_template_string, request
app = Flask(__name__)

TEMPLATE_STRING = """
    <form action="{{ url_for('index') }}" method="post">
    {{request.form['matchup_type']}}<br><br>
    <label><input type="radio" name="matchup_type" value="regular" onclick="this.form.submit()" checked>Regular Season</label>
    <label><input type="radio" name="matchup_type" value="playoffs" onclick="this.form.submit()">Playoffs</label>
    </form>
"""


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template_string(TEMPLATE_STRING)
    else:
        return render_template_string(TEMPLATE_STRING)

第一次打开页面时,只会看到单选按钮。但是,一旦您单击单选按钮,它就会过帐表单,因此现在您将在页面顶部看到所选的值。如果再次单击,则会再次发布该表单,等等。

那么您应该如何解决呢?我认为无需使用此表单进行POST请求,因为您不需要更新任何数据,而只是查询。

    from flask import Flask, render_template_string, request
app = Flask(__name__)

TEMPLATE_STRING = """
    <form action="{{ url_for('history') }}" method="get">
    <select name="owner_id">
    {% for owner in owners %}
      <option {% if owner['id'] == selected_owner_id %} selected {% endif %}value="{{owner['id']}}">{{owner['name']}}</option>
     {% endfor %}
    </select>
    <label><input type="radio" name="matchup_type" value="regular" {%if selected_matchup_type == 'regular'%}checked{%endif%} onclick="this.form.submit()">Regular Season</label>
    <label><input type="radio" name="matchup_type" value="playoffs" {%if selected_matchup_type == 'playoffs'%}checked{%endif%} onclick="this.form.submit()"  >Playoffs</label>
    <br>Queried data goes here
    </form>
"""
owners = [{'id': 1, 'name': 'bob'}, {'id': 2, 'name': 'gary'}, {'id': 3, 'name': 'tom'}]
matchup_types = 'regular', 'playoffs'


@app.route('/history', methods=['GET'])
def history():
    owner_id = request.args.get('owner_id', None, type=int)
    if owner_id not in [owner['id'] for owner in owners]:
        owner_id = owners[0]['id']
    matchup_type = request.args.get('matchup_type', None)
    if matchup_type not in matchup_types:
        matchup_type = matchup_types[0]
    # now you know the owner_id and the matchup type, and know that both are valid, do some query to get table data
    return render_template_string(TEMPLATE_STRING, owners=owners,
                                  selected_owner_id=owner_id,
                                  selected_matchup_type=matchup_type,
                                  matchup_types=matchup_types)

我认为这就是您所需要的。始终不将表单发布为获取请求(<form action="{{ url_for('history') }}" method="get">)。如果值缺失或无效,我们默认返回到某些owner / matchup_type。记住已检查的值,并将其用于呈现模板。

这会将您所有的烧瓶逻辑放入@app.route中,并将您所有的Jinja逻辑放入模板中。

一些一般性评论:

我认为最好不要访问jinja中的request,因为jinja处理错误/丢失值的方式有所不同,并且如果它们是与您的请求相关的逻辑结果,那么很难猜测发生了什么。因此,在python端处理传入的请求。

不是根据选择的值包装2个单选块,而是仅使用一个块并在选项中检查是否符合您的需要。 <option {% if some_value == some_other_value %} checked {% endif%}>blabla</option>

进行更多输入验证!在第一个示例中,模板名称由用户输入的值(匹配类型)决定。但是,如果用户发布了不存在的值怎么办?您遇到错误。

如果两个模板之间的唯一区别是选择了哪个单选按钮,则不需要两个模板。查看更新的版本如何仅在一个模板中处理它。