In Flask you write the route above the method declaration like so:
@app.route('/search/<location>/')
def search():
return render_template('search.html')
However in HTML the form will post to the url in this fashion:
www.myapp.com/search?location=paris
The latter seems to return a 404 from the application where
www.myapp.com/search/london
will return as expected.
I'm sure that there is a simple piece of the puzzle that I'm not getting, but surely the routing engine will consider the query string parameters for meeting the rules requirements.
If not, what is the optimal solution for this scenario as I'm sure 90% of developers must arrive at this point.
The query parameters are not included as part of the route matching, nor are they injected into function arguments. Only the matched URL portions are injected. What you're looking for is request.args
(GET query parameters), request.form
(POST) or request.values
(combined).
You could do something like this if you wanted to support both:
@app.route('/search/<location>')
def search(location=None):
location = location or request.args.get('location')
# perform search
Though, assuming you may want to search on other parameters, probably the best way to do it would be closer to:
def _search(location=None,other_param=None):
# perform search
@app.route('/search')
def search_custom():
location = request.args.get('location')
# ... get other params too ...
return _search(location=location, other params ... )
@app.route('/search/<location>')
def search_location(location):
return _search(location=location)
And so forth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With