如何在flask中获取下拉值并通过url路由更改页面?

sci*_*rer 1 html python jinja2 flask

我想从下拉列表中选择一个值并相应地显示网页。目前,我可以通过在 URL 末尾键入来访问下拉列表中的每个值。我究竟缺少什么?/metadata/table_name1 metadata/table_name2当我在浏览器中输入它时,我就可以访问。但当我从下拉列表中选择该选项时,我无法获取它。下拉列表应重定向到metadata/drop_down_value.

我已经通过打印单独的 url 路由链接进行了测试。通过单击链接,它就可以工作。我需要从下拉列表中选择。

浏览次数:

@app.route('/metadata', methods=['GET', 'POST'])
def metadata():
    cols = None
    table = None
    db_uri = session.get('db_uri', None)
    eng = create_engine(db_uri)
    insp = reflection.Inspector.from_engine(eng)
    tablenames = insp.get_table_names()
    form = SelectTableForm()
    form.table_name.choices = tablenames
    cols = insp.get_columns(table_name=tablenames[0])
    eng.dispose()
    return render_template('tables.html', cols=cols, table=tablenames[0], form=form)

@app.route('/metadata/<table>', methods=['GET', 'POST'])
def select_table(table):
    form = SelectTableForm()
    db_uri = session.get('db_uri', None)
    eng = create_engine(db_uri)
    insp = reflection.Inspector.from_engine(eng)
    tablenames = insp.get_table_names()
    form.table_name.choices = tablenames
    cols = insp.get_columns(table_name=table)
    return render_template('tables.html', cols=cols, table=table, form=form)
Run Code Online (Sandbox Code Playgroud)

形式:

class SelectTableForm(FlaskForm):

    table_name = SelectField(label='Table name', choices=[], coerce=int)
Run Code Online (Sandbox Code Playgroud)

金贾 html:

<!-- This works -->
{% for table in form.table_name.choices %}
    <a href="{{ url_for('select_table', table=table) }}">{{ table }}</a>
{% endfor %}

<!-- This does not -->

<form action="">
    <select name="tables" method="POST" type="submit">
      {% for table in form.table_name.choices %}
          <option value="{{ url_for('select_table', table=table) }}">{{ table }}</option>
      {% endfor %}
    </select>
</form>

<table>
    <tr>
        <th>table</th>
        <th>name</th>
        <th>type</th>
        <th>nullable</th>
        <th>default</th>
        <th>autoincrement</th>
        <th>comment</th>
    </tr>
    {% for col in cols %}
        <tr>
        <td>{{ table }}</td>
        {% for val in col.values() %}
            <td>{{ val }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
</table>
Run Code Online (Sandbox Code Playgroud)

Joo*_*ost 5

您需要一些 js,将当前页面的 url 设置为 select 元素中所选选项的值:onchange="location = this.value;"

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template_string('''
        <select name="form" onchange="location = this.value;">
          {% for table in tables %}
              <option value="{{ url_for('select_table', table=table) }}">{{ table }}</option>
          {% endfor %}
        </select>
''', tables = ['a', 'b'])


@app.route('/select_table/<table>', methods=['GET', 'POST'])
def select_table(table):
    return table
Run Code Online (Sandbox Code Playgroud)