url structure and form posts with Flask


Question

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 as 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...

thanks in advance.

1
5
9/4/2013 5:26:48 PM

Accepted Answer

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.

9
1/5/2012 4:42:02 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon