1
votes

I am trying to get a simple search function going with my flask app. I have the following code that kicks off the search

<form action="/search" method=post>
 <input type=text name=search value="{{ request.form.search }}"></br>
 <div class="actions"><input type=submit value="Search"></div>
</form>

This hooks in with my search/controllers.py script that looks like this

@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'])

Unfortunately whenever I actually search I get a routing error:

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

I tried changing the method to methods=['POST'] but it made no difference.

2

2 Answers

3
votes

Use url_for('index') to generate the correct url for the action.

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

Currently, you're submitting to the url without the trailing /. Flask redirects this to the route with the trailing /, but POST data doesn't survive redirects on many browsers, so Flask is warning you about the issue.

0
votes

As the error states, your form is posting to /search but your handler is set up for /search/. Make them the same.