keeping forms data in url with flask

2019-08-03 06:38发布

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

1条回答
Anthone
2楼-- · 2019-08-03 07:03

The HTML form you create ends up looking like this:

<form action="/search" method=post>
    <p><input type="text" name="query" value="test"></p>
    <p><input type="submit" value="Search"></p>
    <br />
</form>

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.

<form action="/search">
    <p><input type="text" name="query" value="test"></p>
    <p><input type="submit" value="Search"></p>
    <br />
</form>

Note that if you do this you'll also need to change your "search" view..

@app.route('/search')
def search():
    return request.args['query']

Note here that I've removed the methods=['POST'] part, so now the search view will accept the GET request. Also, I'm using request.args rather than request.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.

查看更多
登录 后发表回答