Menu Close

Flask Request Object

Flask Request Object

In this python flask guide, we are going to learn all about Python flask request objects with help of examples. In the previous, tutorial, we have seen all about how to render HTML files in the flask application.

Note:- You should have basic knowledge of Python programming to understand flask coding. You can learn Python from our Python tutorial.

Flask Request Object

As we know that all web applications are based on the client-server architecture. The flask request object is capable of getting all the information sent from the client to the server.
As we discussed in our previous tutorial, Every request performs on the basis of HTTP methods.

Let’s understand the flask request object with the help of an example.

Retrieve form data

In this flask example, we will get all the form data using the flask request object.

templates/users.html:


<html>
<head>
<title>
Flask website
</title>
</head>
<body>

<h1>User Registration Form</h1>

<form method="POST" action="/success">
<label>Username:- </label>
<input type="text" name="username" placeholder="Enter your username"><br><br>
<label>Email:- </label>
<input type="email" name="email" placeholder="Enter your email"><br><br>
<label>Password:- </label>
<input type="password" name="password" placeholder="Enter your password">
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

main.py:


from flask import Flask, render_template, request

#Create the object of the Flask class.
app= Flask(__name__)

@app.route("/user-registration")
def Home():
    return render_template("users.html")
    
    
@app.route("/success", methods=['POST'])    
def success():
    user = {}
    username = request.form['username']
    email = request.form['email']
    password = request.form['password']
    
    user.update({"username": username, "email": email,"password":password})
    return user

if __name__ == '__main__':
    app.run(debug=True)

When you execute the above flask script file and visit http://127.0.0.1:5000/user-registration then it will ask you to fill the form and submit it. After submitting the form you will all the data which have filled up in the form.

Conclusion

In this example, you have learned all about the Python flask request object with the help of an example.
the request object is the most important in a flask to get the request data. You can get JSON and Header data except form data using the flask request object.

If you like this flask request object article, please keep continuing the flask and other tutorials.

Python Flask Tutorials


Previous Article
Next Article

Related Posts