Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Url structure and form posts with Flask

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.

like image 988
Jay Avatar asked Jan 04 '12 23:01

Jay


1 Answers

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.

like image 179
twooster Avatar answered Oct 09 '22 15:10

twooster