Flask request.form: Usage Guide
In Python, request.form is a dictionary used to retrieve form data passed through the HTTP POST method.
You can use request.form to retrieve the values of the fields in the form. For example, assuming the form contains a field named username, you can use request.form[‘username’] to get the value of that field.
Here is a simple example:
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
username = request.form['username']
return f"Hello, {username}!"
else:
return "Please submit the form."
if __name__ == '__main__':
app.run()
In the example above, if a POST request is received, retrieve the value of the username field from request.form and return a welcome message containing that value. If a GET request is received, return a message asking to submit the form.
It is important to note that when using request.form to retrieve form data, you need to ensure that the Content-Type of the request is application/x-www-form-urlencoded or multipart/form-data. Additionally, if a field does not exist, it will raise a KeyError exception, which can be avoided by using the get() method.
For more information about request.form, please refer to the Flask official documentation: https://flask.palletsprojects.com/en/2.0.x/api/?highlight=request.form#flask.Request.form