Skip to content

[Python] Flask Study Notes (3): Get and Post commands in request method

Last Updated on 2021-06-30 by Clay

The last experience note recorded the use of render_template() to render html files through the Flask framework, so today I will briefly record how to interact with html through request.

The common methods of Flask request are Get and Post. The sample programs are recorded separately below.


Get

The Get command in the request, at the name suggests, is to get the data on the webpage. A common type is to get the parameter on the URL.

Let's take a simple example:

# -*- coding: utf-8 -*-
from flask import Flask, request


app = Flask(__name__)


@app.route('/', methods=['GET'])
def main():
     name = request.args.get('name')
     return 'My name is {}'.format(name)


if __name__ == '__main__':
     app.run(host='127.0.0.1', port=8000)



Output:

First, we need to import the request-related package and use request.args.get('name') in the code to get the value of the parameter name. Then we enter the value after "My name is".

But when you open the picture, you can see that the next parameter is not any parameter, but "None"; this is because we haven't entered the value of the parameter name.

Then let's enter it.

how is it? Is the name "Clay" displayed? This is the parameter obtained using request.args.get().


Post

Post is different from simple Get. Common Post is mostly used for interaction with HTML. Maybe this explanation is not clear, let's try to make a "login interface" directly below.

The first is to write an HTML login file login.html (the format of sending Post parameters must be form):

<body style="background-color: black">
     <form method="post" action="/login">
         <input type="text" name="user">
         <button type="submit">Submit</button>
     </form>
</body>



Then write an HTML file result.html that accepts input parameters to jump to:

<body style="background-color: black">
     <p style="color: white">Your user name is {{ name }}</p>
</body>



# -*- coding: utf-8 -*-
from flask import Flask, render_template, request


app = Flask(__name__)


@app.route('/')
def main():
     return render_template('login.html')


@app.route('/login', methods=['POST'])
def result():
     if request.method == 'POST':
         user = request.values['user']
         return render_template('result.html', name=user)


if __name__ == '__main__':
     app.run(host='127.0.0.1', port=8000)



Output:

這是 login.html 呈現的界面

Then we enter "Clay" and click Submit button.



Then we will see the result after the jump page, and the URL will be changed from the root directory to "/login".

We can complete all kinds of web functions through this interactive method.


References


Read More

Leave a Reply