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


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:

HTML
<!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.

Python3
# 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:

The user enters a number when the page is rendered for URL ‘localhost:5000/square’

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.



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.

Similar Reads

Flask HTTP Methods

In a Client-Server architecture, there is a set of rules, called a protocol, using which, we can allow the clients, to communicate with the server, and, vice-versa. Here, the Hyper Text Transfer Protocol is used, through which, communication is possible. For example, Our browser, passes our query, to the Google server, receiving which, the Google server, returns relevant suggestions. The commonly used HTTP methods, for this interconnection, are – GET and POST.4...

GET Method in Flask

The request we type, in the browser address bar, say: ‘http://google.com’ is called the Uniform Resource Locator.  It mentions the address we are looking for, in this case, the Google landing(starting) page.  The browser, sends a GET request, to the Google server, which returns the starting webpage, in response. The GET request is simply used, to fetch data from the server. It should not be used, to apply changes, to the server data....

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....

Contact Us