in this tutorial, we will see the HTTP Get and Post methods in Flask using python programming language.
Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol.
The following table to recall the different HTTP methods −
|Sr.No||Methods & Description|
Sends data in unencrypted form to the server. Most common method.
Same as GET, but without response body
Used to send HTML form data to server. Data received by POST method is not cached by server.
Replaces all current representations of the target resource with the uploaded content.
Removes all current representations of the target resource given by a URL
By default, the route of the flask will respond to the GET requests. Anyhow, this preference can be altered by providing methods argument to route() decorator.
To determine the use of POST method in URL Routing, let us create an HTML form and use the POST method to send form data to a URL.
<html> <body> <form action = "http://localhost:5000/login" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html>
Now enter the following script in Python shell.
from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/success/
') def success(name): return 'welcome %s' % name @app.route('/login',methods = ['POST', 'GET']) def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success',name = user)) else: user = request.args.get('nm') return redirect(url_for('success',name = user)) if __name__ == '__main__': app.run(debug = True)
After the development server starts running, open /login.html in the browser, enter name in the text field and click Submit.
Form data is POSTed to the URL in action clause of the form tag.
http://localhost/login is mapped to the login() function. Since the server has received data by POST method, a value of ‘nm’ parameter obtained from the form data is obtained by –
user = request.form['nm']
It is passed to /success URL as variable part. The browser displays a welcome message in the window.
Change the method parameter to ‘GET’ in login.html and open it again in the browser. The data received on the server is by the GET method. The value of ‘nm’ parameter is now obtained by –
User = request.args.get(‘nm’)
Here, args is dictionary object containing a list of pairs of form parameter and its corresponding value. The value corresponding to ‘nm’ parameter is passed on to ‘/success’ URL as before.
Get More Post On Python