POST Method in Flask
Suppose, we need to register our details, to a website, OR, upload our files, we will send data, from our browser(the client) to the desired server. The HTTP method, preferred here, is POST. The data sent, from HTML, is then saved, on the server side, post validation. The POST method should be used, when we need to change/add data, on the server side.
File Structure
Example of HTTP POST in Flask
In this example, we will consider, the same landing page, giving us facts, about Math calculations, and, allowing us to enter a number, and, return its square. Let us see the example:
Step 1: The same HTML page, called ‘squarenum.html‘, is in the templates folder. At the backend side, we will write, appropriate logic, in a view function, to get the number, entered by the user, and, return the same, in the ‘answer.html’ template. The frontend code file is as shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Square Of Number!</title>
</head>
<body>
<h1><i> Welcome to the Maths page!</i></h1>
<p>Logic shapes every choice of our daily lives.<br>
Logical thinking enables someone to learn and
make decisions that affect their way of life. !</p>
<form method="POST" action ="#">
Enter a number :
<input type="text" name="num" id="num"></input>
<input type="submit" name="btnnum" id="btnnum"></input>
</form>
</body>
</html>
Step 2: The view function squarenumber(), now also contains value POST in the ‘methods’ attribute, in the decorator. Thus, when the user requests the page, the first time, by calling “http://localhost:5000/square”, a GET request will be made. Here, the server will render, the corresponding “squarenum.html”, webpage. After clicking on Submit, on entering a number, the data is posted back, to the same webpage. Here, the POST method, sends data, in the message body, unlike GET, which appends data in the URL. In the view function, the If-Else condition block, retrieves the number, by accessing the ‘form’ attribute, of the request. The square of the number is calculated, and, the value is passed to the same “answer.html” webpage, using the Jinja2 template.
# import the Flask library
from flask import Flask, render_template, request
# Create the Flask instance and pass the Flask constructor the path of the correct module
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def squarenumber():
# If method is POST, get the number entered by user
# Calculate the square of number and pass it to answermaths
if request.method == 'POST':
if(request.form['num'] == ''):
return "<html><body> <h1>Invalid number</h1></body></html>"
else:
number = request.form['num']
sq = int(number) * int(number)
return render_template('answer.html',
squareofnum=sq, num=number)
# If the method is GET,render the HTML page to the user
if request.method == 'GET':
return render_template("squarenum.html")
# Start with flask web app with debug as True only
# if this is the starting page
if(__name__ == "__main__"):
app.run(debug=True)
Output:
On clicking the Submit button, the data is posted back, to the server, and, the result page is rendered. Please note, the value entered, is not visible in the URL now, as the method used, is POST.
Related Articles: Difference between GET and POST
Flask – HTTP Method
In this article, we will learn how to handle HTTP methods, such as GET and POST in Flask using Python. Here, we will understand the concept of HTTP, GET, and HTTP POST, and then we will the example and implement each in Flask. Before starting let’s understand the basic terminology:
- GET: to request data from the server.
- POST: to submit data to be processed to the server.
- PUT: A PUT request is used to modify the data on the server. It replaces the entire content at a particular location with data that is passed in the body payload. If there are no resources that match the request, it will generate one.
- PATCH: PATCH is similar to a PUT request, but the only difference is, it modifies a part of the data. It will only replace the content that you want to update.
- DELETE: A DELETE request is used to delete the data on the server at a specified location.
Related Article: Flask HTTP methods, Handle GET & POST requests
Contact Us