What is HTTP?
HTTP is defined as HyperText Transfer Protocol. In World Wide Web, HTTP is considered the foundation of data transfer over the network. There are different methods of data transfer defined in the HTTP (protocol), I have tried listing some below:
- GET – Sends data in unencrypted form to the server. Most common method.
- POST – Used to send HTML form data to the server. Data received by the POST method is not cached by the server. Also, large data can be sent using the POST method
- PUT – Replaces all current representations of the target resource with the uploaded content.
- DELETE – Removes all current representations of the target resource given by a URL.
As in other languages, the default method of data transfer is GET which can be changed to POST by explicitly mentioning it into the route() decorator function.
To understand this better, let us create two files. The first file will contain the HTML form which we will use to send data. While the second will contain the python flask script to catch the data coming from the first file.
HTML FILE WITH FORM CODE
<html> <body> <form action = "http://localhost:5000/signin" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "usernaem" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html>
PYTHON FLASK FILE
from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/dashboard/<name>') def success(name): return 'welcome %s' % name @app.route('/login',methods = ['POST', 'GET']) def login(): if request.method == 'POST': user = request.form['username'] return redirect(url_for('success',name = user)) else: user = request.args.get('username') return redirect(url_for('success',name = user)) if __name__ == '__main__': app.run(debug = True)
Now, turn on the python server from terminal / command prompt and in the browser, open the HTML file. Fill in the form and hit the submit button. What you will see is, the welcome message on the next page.
In the first case, the line of code to receive the data in POST method is
Now change the method to GET in HTML file, form tag. And try to submit the form again from the browser, now also you will see the same message on the browser. But this time if you notice, then you will be able to see that the data is being passed in the URL, and is using the GET method, so the data is being received by another statement, i.e.
So, now you know how to pass and receive data using HTTP GET & POST methods in Flask.
As we move on, there are lot more interesting things, stay tuned.