使用python flask搜索应用程序路由错误

Routing error with python flask search app

我正在尝试使用我的flask应用程序获得一个简单的搜索功能。我有以下代码开始搜索

1
2
3
4
<form action="/search" method=post>
 <input type=text name=search value="{{ request.form.search }}"></br>
 <input type=submit value="Search">
</form>

这与我的search/controllers.py脚本挂钩,该脚本如下所示

1
2
3
4
5
6
7
8
@search.route('/search/')
@search.route('/search/<query>', methods=['GET', 'POST'])
def index(query=None):
    es = current_app.config.get("es")

    q = {"query":{"multi_match":{"fields":["name","tags","short_desc","description"],"query":query,"fuzziness":"AUTO"}}}
    matches = es.search('products', 'offerings', body=q)
    return render_template('search/results.html', services=matches['_source'])

不幸的是,每当我实际搜索时,都会得到一个路由错误:

FormDataRoutingRedirect: A request was sent to this URL (http://localhost:8080/search) but a redirect was issued automatically by the routing system to"http://localhost:8080/search/". The URL was defined with a trailing slash so Flask will automatically redirect to the URL with the trailing slash if it was accessed without one. Make sure to directly send your POST-request to this URL since we can't make browsers or HTTP clients redirect with form data reliably or without user interaction. Note: this exception is only raised in debug mode

我试着把方法改成methods=['POST'],但没什么区别。


使用url_for('index')为操作生成正确的URL。

1
<form action="{{ url_for('index') }}">

目前,您提交的URL没有后面的/。flask使用尾随的/将其重定向到路由,但是post数据在许多浏览器上都无法保存重定向,因此flask警告您有关此问题。


在错误状态下,表单将发布到/search,但处理程序已设置为/search/。使它们相同。