使用表单对Flask进行“高级搜索”的正确方法是什么?

时间:2015-01-13 17:30:38

标签: python forms flask wtforms flask-wtforms

我尝试设置一个高级搜索,允许按代码,国家/地区,标题搜索产品。我的views.py内有:

@app.route('/advanced_search_results/<code>/<country>/<title>', methods=['GET', 'POST'])
def advanced_search_results(code, country, title):
    products = models.Product.query.filter_by(code=code, country=country, title=title).all()
    return render_template('advanced_search_results.html', products=products)   


@app.route('/advanced_search', methods=['GET', 'POST'])
def advanced_search():
    form = AdvancedSearchForm()
    if form.validate_on_submit():
        code = form.code.data
        country = form.country.data
        title = form.title.data
        return redirect(url_for('advanced_search_results', code=code, country=country, title=title))
    return render_template('advanced_search.html', title='Advanced Search', form=form)

这里有一些明显的问题,但最让我担心的是,高级搜索最终会出现在 www.mysite.com/advanced_search_results/the_code/the_country/the_title 等网址上。随着搜索越来越高,字符串只会变长。我是朝着正确的方向前进还是我错过了更好的处理方式?

1 个答案:

答案 0 :(得分:1)

您可以使用查询字符串 - 即您的网址如下所示:

  

mysite.com/advanced_search_results?country=USA&code=42&title=aTitle

from flask import request
@app.route('/advanced_search_results')
def adv_search_results():
    country = request.args.get('country')
    code = request.args.get('code')
    title = request.args.get('title')
    products = models.Product.query.filter_by(code=code, country=country, title=title).all()
    return render_template('advanced_search_results.html', products=products)

另请注意unknown variables in url_for() will be appended as query parameters.