What is Routing?

Imagine you go to a restaurant to eat: the waiter won’t take you directly to the kitchen. Instead, based on the dish you ordered (e.g., “Kung Pao Chicken”), they guide you to the chef responsible for that dish. In web development, routing is like the restaurant waiter. It receives the URL entered by the user in the browser (e.g., http://example.com/home), finds the corresponding “chef” (a handler function), and lets the chef respond (return a webpage or data).

Why Do We Need Routing?

When users visit different pages of a website (e.g., home page, user center, article details page), routing helps:
1. Receive the user’s request (e.g., “visit /about”)
2. Match the corresponding processing logic (e.g., “display the ‘About Us’ page”)
3. Return the result to the user (e.g., webpage content or JSON data)

Implementing Your First Route with Flask (Basic)

Let’s take Flask, the most popular lightweight framework, to implement a simple route.

Step 1: Install Flask

First, ensure Flask is installed:

pip install flask

Step 2: Write a Basic Route

from flask import Flask  # Import the Flask class

app = Flask(__name__)  # Create a Flask application instance

# Define a route: When accessing the root path '/', execute the index function
@app.route('/')
def index():
    return "Hello, Web! This is the home page~"  # Return response content

# Run the application
if __name__ == '__main__':
    app.run(debug=True)  # debug=True enables debug mode

Effect:

After running the code, visit http://127.0.0.1:5000/ to see “Hello, Web! This is the home page~”.

Advanced: Routing with Parameters

If you need to dynamically get user input (e.g., accessing /user/123 to get a user ID), use <parameter_name> to define the route.

Example: Get Username

@app.route('/user/<username>')  # <username> is a parameter passed to the user_profile function
def user_profile(username):
    return f"Welcome to the user's homepage: {username}!"

# Visiting http://127.0.0.1:5000/user/Xiaoming will show: Welcome to the user's homepage: Xiaoming!

Advanced: Typed Parameters

Parameters can specify types (e.g., int, float, path) for automatic type conversion:

@app.route('/post/<int:post_id>')  # <int:post_id> indicates the parameter is an integer
def show_post(post_id):
    return f"Viewing article ID: {post_id}"

# Visiting http://127.0.0.1:5000/post/123 will show: Viewing article ID: 123

Handling Different HTTP Requests (GET/POST)

Different pages may require different request methods (e.g., the home page uses GET to fetch content, and a login form uses POST to submit data). Routing can specify allowed request methods via the methods parameter.

Example: Route Supporting GET and POST

from flask import request  # Import the request object to access request information

@app.route('/login', methods=['GET', 'POST'])  # Allow GET and POST methods
def login():
    if request.method == 'POST':  # Check the request method
        return "Login successful!"
    else:
        return "Please enter your account and password (form page)"  # Show form on GET request

Key Points:

  • GET: Default method for fetching data (e.g., opening a webpage)
  • POST: Used for submitting data (e.g., form submissions, file uploads)
  • If only one method is allowed, methods can be omitted (default is only GET)

Routing “Reverse Lookup” (url_for)

Sometimes you need to dynamically generate route URLs in code (e.g., in templates for navigation). Use the url_for function.

Example: Generate Route URLs

from flask import url_for

@app.route('/')
def index():
    # Generate the URL for /user/Xiaoming, corresponding to the user_profile function
    user_url = url_for('user_profile', username='Xiaoming')
    return f"Homepage link: <a href='{user_url}'>Xiaoming's homepage</a>"

@app.route('/user/<username>')
def user_profile(username):
    return f"User homepage: {username}"

Summary

Routing is the core of Python web development that connects user requests to processing logic. Key usages:
1. Basic Routing: Define with @app.route('/path') to map to a view function
2. Dynamic Parameters: Use <parameter_name> or <type:parameter_name> to receive user input
3. Request Methods: Specify supported HTTP methods via methods
4. Reverse Resolution: Use url_for to generate route URLs, avoiding hardcoding

Once you master routing, you can easily implement page navigation and data interaction!

Xiaoye