Flask - HTTP Methods
Flask – HTTP methods
Section titled “Flask – HTTP methods”The HyperText Transfer Protocol (HTTP) is the foundation of data communication on the World Wide Web. It defines a set of request methods (often called “HTTP verbs”) to indicate the desired action to be performed for a given resource (identified by a URL).
Common HTTP Methods:
| Sr.No | Method | Description |
|---|---|---|
| 1 | GET | Requests retrieval of information identified by the Request-URI. Should only retrieve data and have no other effect. This is the most common method used when browsing. |
| 2 | POST | Submits data to be processed to the identified resource (e.g., submitting a web form, uploading a file). Often results in a change in state or side effects on the server. |
| 3 | PUT | Replaces all current representations of the target resource with the request payload. Often used for updating an existing resource entirely. |
| 4 | DELETE | Requests that the origin server delete the resource identified by the Request-URI. |
| 5 | HEAD | Identical to GET except that the server MUST NOT return a message-body in the response. Useful for retrieving meta-information about the resource without transferring the entire content. |
| 6 | OPTIONS | Requests information about the communication options available for the target resource (e.g., which HTTP methods are supported). |
| 7 | PATCH | Applies partial modifications to a resource. Unlike PUT, it only updates the specified fields. |
Specifying Methods in Flask Routes
Section titled “Specifying Methods in Flask Routes”By default, Flask routes only respond to GET requests (and implicitly HEAD and OPTIONS). To allow a route to handle other methods, you must explicitly list them using the methods argument in the @app.route() decorator.
Example: Handling GET and POST for a Login Form
Section titled “Example: Handling GET and POST for a Login Form”This example demonstrates a single URL (/login) that displays a form when accessed via GET and processes the submitted form data when accessed via POST.
- Create an HTML template named
login_page.htmlin yourtemplatesfolder:
<!DOCTYPE html><html><head> <title>Login Example</title></head><body> <h1>Login Form</h1> <form action="{{ url_for('handle_login') }}" method="post"> <p>Enter Name: <input type="text" name="username"></p> <p><input type="submit" value="Submit"></p> </form></body></html>Note the method="post" in the <form> tag.
- Create the Flask application script (
app.py):
from flask import Flask, redirect, url_for, request, render_template
app = Flask(__name__)
# Route for successful login@app.route('/success/<name>')def login_success(name): return f'Welcome {name}!'
# Route to handle both displaying the form (GET) and processing it (POST)@app.route('/login', methods=['POST', 'GET'])def handle_login(): if request.method == 'POST': # Request is POST: access form data submitted user_name = request.form['username'] # Access data using the input's 'name' attribute # Redirect to the success page, passing the username return redirect(url_for('login_success', name=user_name)) else: # Request is GET: display the login form template return render_template('login_page.html')
if __name__ == '__main__': app.run(debug=True)Explanation:
methods=['POST', 'GET']: This explicitly allows the/loginroute to handle both POST and GET requests.request.method: Inside thehandle_loginfunction, we check the current request’s method.- If
request.method == 'POST': This block executes when the form is submitted. We retrieve the value of the input field namedusernamefromrequest.form(which holds form data submitted in the request body). Then, we redirect the user to thelogin_successroute, building the URL withurl_forand passing the extracteduser_name. - If
request.method == 'GET'(theelseblock): This executes when the user first navigates to/login. We render thelogin_page.htmltemplate to display the form. request.args: If data were sent via the URL query string (e.g.,/search?term=flask), you would access it usingrequest.args.get('term'). This is typical for GET requests.
Running the Example:
-
Save the files and run
python app.py. -
Open your browser and go to
http://127.0.0.1:5000/login. You’ll see the login form (handled by the GET request). -
Enter a name (e.g., “Alice”) and click Submit.
Description of interaction:
The browser sends a POST request to /login with the name you entered in the form data. Flask routes this to handle_login(). The if request.method == 'POST' block executes, retrieves “Alice” from request.form['username'], and generates a redirect response to /success/Alice. The browser receives this redirect and makes a new GET request to /success/Alice. Flask routes this to login_success(name='Alice'), which returns the “Welcome Alice!” message.