Flask http method - GET & POST request

This blog is all about Flask HTTP requests. Flask has different methods to handle HTTP requests, HTTP protocol is the basis for data communication in the WWW. 

Flask has different methods, which are the following - 

MethodDescriptions

  GET

  This method will send a GET message, and the server will return the data.

  POST

  This method will send form data to the server.

  HEAD

  Same as the GET method but this method have no response body.
  PUT  This method is used to replace all current representations of the target resource with uploaded data.

 DELETE

  This method is used to delete all current representations provided by the URLs.

So, after this all first we will start with the Routing.

What is Routing? 

A name that is meaning full and easy to remember, So that users can easily access the webpage by using that name. 

Example - 

            www.interntuts.com/ products

In this example, we can say the route to the keyword " products "

So let's try to access a web page with the help of a route. First of all, create a .py file start flask. Create a file with the name hello.py and write the following code inside the file.


from flask import Flask

app = Flask(__name__)

@app.route("/hello")
def hello():
	return "welcome to flask"
    

So after this, let's start with the variables rule means we can pass arguments with the URLs.And also can use convert with the URL argument.

Converters are - 

  • string
  • int
  • float
  • path
  • uuid
Variable Rule Example - 

Code Example - 1


@app.route('/user/username')
def show_user_profile(username):
    # show the username
    return f'Username: {username}'
    

Code Example - 2


@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f'Post {post_id}'

HTTP Methods

Web applications use different HTTP methods when accessing URLs.By default, a route only answers GET requests. But Now we are going to start with HTTP methods and here we will see the GET and POST methods.

Let's see a small code of HTTP methods : 


from flask import Flask,request

app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
    	form_data = request.form
        
        return form_data
    else:
    	# this will be the GET method, here we can load our html form.
        return "load form"

In this Blog we had completed some basic this about flask, In the next post we will see how we can perform crud operations in flask with the help of MySQL database.

Comments