Flask Request Methods: Practical Handling of GET and POST Requests

I. What is Flask?

Flask is a lightweight Python Web framework that allows you to quickly build web applications. Despite its simplicity, it offers powerful functionality, making it ideal for beginners to get started with web development.

II. Why Learn About GET and POST?

In web development, browsers and servers communicate through HTTP requests. The two most common request methods are:

  • GET: Used to retrieve data from the server (e.g., loading a webpage, searching for information)
  • POST: Used to submit data to the server (e.g., login forms, file uploads)

III. Installing Flask

First, ensure Python is installed. Then run this command in your terminal:

pip install flask

IV. Core Differences Between GET and POST

Comparison GET POST
Data Location In the URL (e.g., /page?name=Zhang) In the request body (not visible in URL)
Purpose Retrieving data Submitting data (e.g., forms)
Security Data is exposed, not suitable for sensitive info More secure
Caching Can be cached by browsers Usually not cached

Real-life analogy:
- GET: You ask a waiter, “What dishes do you have today?” (Data is displayed on the menu)
- POST: You say, “I’ll have a steak.” (The waiter notes it down, not written on the menu)

V. Practical Example: Handling Login Form with Flask

We’ll create a simple login page that uses GET to display the form and POST to process submissions.

1. Project Structure

myapp/
├── app.py          # Main application file
└── templates/      # Template folder
    └── login.html  # Login form page

2. Writing the Main Application (app.py)

# Import Flask core class and request handling module
from flask import Flask, render_template, request

# Create Flask application instance
app = Flask(__name__)

# Define route supporting both GET and POST requests
@app.route('/login', methods=['GET', 'POST'])
def login():
    # Check request method
    if request.method == 'POST':
        # Get form data (ensure form field names match HTML)
        username = request.form.get('username')
        password = request.form.get('password')

        # Simple validation
        if username and password:
            return f"Login successful! Welcome back, {username}!"
        else:
            return "Username or password cannot be empty!"
    else:
        # For GET request: return login form page
        return render_template('login.html')

# Run the application (debug=True enables auto-reload during development)
if __name__ == '__main__':
    app.run(debug=True)

3. Creating the Login Form Template (templates/login.html)

Create login.html in the templates folder:

<!DOCTYPE html>
<html>
<head>
    <title>User Login</title>
    <style>
        body { font-family: Arial; margin: 20px; }
        .form-group { margin-bottom: 10px; }
    </style>
</head>
<body>
    <h1>User Login</h1>
    <!-- Form submission via POST to /login route -->
    <form method="POST" action="/login">
        <div class="form-group">
            <label>Username:</label>
            <input type="text" name="username" required>
        </div>
        <div class="form-group">
            <label>Password:</label>
            <input type="password" name="password" required>
        </div>
        <button type="submit">Login</button>
    </form>
</body>
</html>

VI. Running and Testing

  1. Run in terminal: python app.py
  2. Visit in browser: http://localhost:5000/login
  3. Enter username and password, then click “Login”

Key Knowledge Explanation:

  • Route Configuration: methods=['GET', 'POST'] enables a single route to handle both request types
  • Form Submission: method="POST" sends data in the request body, action="/login" specifies the target route
  • Data Retrieval: request.form.get('username') extracts form fields from POST requests (safe handling of empty values)
  • Template Rendering: render_template('login.html') loads the HTML template from the templates folder

VII. Common Issues and Notes

  1. How to restrict to POST only?
    Modify the route to: @app.route('/login', methods=['POST']) - GET requests will return 405 error

  2. How to get URL parameters (GET data)?
    Use request.args.get('param_name'):

   @app.route('/search')
   def search():
       keyword = request.args.get('keyword')  # From URL: /search?keyword=Python
       return f"Search content: {keyword}"
  1. Security Tip:
    Sensitive data (e.g., passwords) must use POST, and HTTPS should be enabled in production. Add CSRF protection (e.g., with Flask-WTF) for real-world projects.

VIII. Extension Exercises

Try modifying the code to:
- Create a user registration page handling both GET and POST
- Add a “Remember Me” option (via hidden form field)
- Improve error handling (e.g., duplicate submissions, invalid data formats)

With these examples, you’ve mastered basic GET/POST handling in Flask. Next, explore databases, session management, and other advanced features to enhance your web development skills!

Xiaoye