Despite looking at URL building howtos with Flask, I couldn't figure out a way to keep form data in url.
This code works fine :
@app.route('/', methods=['GET'])
def index():
res = '''<form action="/search" method=post>
<p><input type="text" name="query" value="test"></p>
<p><input type="submit" value="Search"></p>
<br />
</form>'''
return res
@app.route('/search', methods=['POST'])
def search():
return request.form['query']
But results are displayed on myapp.com/search
while I would like something like myapp.com/search?query=toto
I must have missed something pretty basic I guess... Any hint ?
Thanks in advance
The HTML form you create ends up looking like this:
Note the
method=post
part. This tells the browser to use POST rather than GET when submitting the form. When it uses POST, the data is included in the body of the resulting request. When you use GET, the data is included in the URL. So, remove this part of your HTML so your form looks like this instead and the browser will make a GET request.Note that if you do this you'll also need to change your "search" view..
Note here that I've removed the
methods=['POST']
part, so now the search view will accept theGET
request. Also, I'm usingrequest.args
rather thanrequest.form
. See the API Documentation for the difference.For more info, see the answers on When should I use GET or POST method, or search for other sites that describe the difference (such as this site).
Understanding the difference between GET and POST (and specifically how HTTP and HTML work to make requests from the browser to the server) is absolutely necessary to understand how web frameworks like Flask work.