url structure and form posts with Flask


In Flask you write the route above the method declaration like so:

def search():
  return render_template('search.html')

However in HTML as form will post to the url in this fashion


the latter seems to return a 404 from the application where


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.

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:

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

def search_custom():
    location = request.args.get('location')
    # ... get other params too ...
    return _search(location=location, other params ... )

def search_location(location):
    return _search(location=location)

And so forth.

1/5/2012 4:42:02 AM

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