Flask-格式化网站网址以显示搜索查询

时间:2018-10-21 09:58:27

标签: python html flask

我想显示来自https://website.com/search?q=query之类的URL中的表单的搜索。我该如何在烧瓶中做到这一点?

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired

class SearchForm(FlaskForm):
    search = StringField('search', validators=[DataRequired()])

main.py

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = SearchForm()
    query = form.data['search']
    if query != '':
        items = Foo.query.filter(Foo.name.like('%'+query+'%')).all()
        table = ItemTable(items)
        return render_template('index.html', form=form, query=query, table=table)
    return render_template('index.html', form=form)

templates / index.html

{% block page_content %}
<div class="page-header">
  <form style="display: inline;" action="{{ url_for('index') }}" method="post" name="search">
    {{ form.search(size=20) }}
    <input type="submit" value="Search">
  </form>

  {% if table %}
    <h1>Search results for "{{ query }}":</h1>
    {{ table }}
  {% endif %}
</div>
{% endblock page_content %}

1 个答案:

答案 0 :(得分:1)

在您的示例https://website.com/search?q=query中,URL命名空间为search,而q是GET请求参数。为了在Flask中实现此功能,您需要在/search处路由视图,并从GET请求参数中检索q。 WTForms允许您的窗体根据您的实例使用GET或POST方法。 Flask的文档here中对此进行了描述。

最后,您的代码可以如下所示:

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired

class SearchForm(FlaskForm):
    q = StringField('q', validators=[DataRequired()])

main.py

@app.route('/', methods=['GET'])
@app.route('/search', methods=['GET'])
def index():
    form = SearchForm(request.args)
    query = request.args.get('q', None)
    table = None
    if query is not None:
        items = Foo.query.filter(Foo.name.like('%'+query+'%')).all()
        table = ItemTable(items)
    return render_template('index.html', form=form, query=query, table=table)

templates / index.html:

{% block page_content %}
<div class="page-header">
  <form style="display: inline;" action="{{ url_for('index') }}" method="get" name="search">
    {{ form.q(size=20) }}
    <input type="submit" value="Search">
  </form>

  {% if table %}
    <h1>Search results for "{{ query }}":</h1>
    {{ table }}
  {% endif %}
</div>
{% endblock page_content %}

我还对您的代码进行了一些重构,因为针对几乎相似的逻辑两次调用render_template似乎很多余。