Flask Introduction: Mastering Routes and View Functions from Scratch

Flask is a lightweight Python Web framework, loved by developers for its simplicity and flexibility. For beginners with no prior experience, mastering routes and view functions is the first step in learning Flask. This article will guide you from installing Flask to understanding route definition, the role of view functions, and how they work together.

一、Installing Flask

To start using Flask, you first need to install it. Ensure Python (recommended version 3.6 or higher) is installed on your computer. Open your command line tool and run the following command:

pip install flask

After installation, verify it by executing import flask in the Python terminal (no error messages indicate success).

二、First Flask Application: “Hello, Flask!”

Let’s begin with the simplest example to create a web app that returns “Hello, Flask!”. Create a new Python file (e.g., app.py) and enter the following code:

# Import the Flask class
from flask import Flask

# Create a Flask application instance; __name__ is the current module name
# Flask uses this to locate resource paths
app = Flask(__name__)

# Define routes and view functions
@app.route('/')  # Decorator: Binds the URL path '/' to the following function
def index():     # View function: Handles user requests
    return "Hello, Flask!"  # Return response content

# Start the development server
if __name__ == '__main__':
    app.run(debug=True)  # debug=True: Enables debug mode for auto-reloading

Run the code:

python app.py

Flask will start a local development server at http://127.0.0.1:5000/. Visit this URL in your browser to see “Hello, Flask!”.

三、Routes: Mapping URLs to Functions

Routes are a core concept in Flask, defining the correspondence between a user request URL and the view function that handles it. Think of it as: “When a user visits a URL, Flask automatically calls the corresponding view function and returns the function’s output as the response.”

1. Static Routes: Fixed Paths

In the example above, @app.route('/') maps the root path / to the index function. You can define other fixed paths:

@app.route('/about')  # Accessible at http://127.0.0.1:5000/about
def about():
    return "About us page"

@app.route('/contact')  # Accessible at http://127.0.0.1:5000/contact
def contact():
    return "Contact us page"

Visiting /about or /contact triggers the respective functions and returns their content.

2. Dynamic Routes: Paths with Parameters

For variable paths (e.g., user profiles like /user/Alice or /user/Bob), use dynamic parameters in routes. Syntax: <parameter_name>, and pass the parameter to the view function.

@app.route('/user/<username>')  # <username> matches any string
def user_profile(username):
    return f"Welcome to {username}'s profile page!"

When a user visits http://127.0.0.1:5000/user/Alice, the username parameter is set to "Alice", and the view returns the greeting.

Note: Dynamic parameters can specify types (e.g., integers, floats):

@app.route('/post/<int:post_id>')  # Only matches integer post_id
def show_post(post_id):
    return f"Displaying post ID: {post_id}"

Visiting /post/123 returns the post ID, while /post/abc (non-integer) results in a 404 error.

四、View Functions: Handling Requests and Returning Responses

View functions are the “executors” of routes. They receive user requests (e.g., URL parameters, form data) and return responses (web pages, JSON, redirects, etc.).

1. Returning Strings or HTML

The simplest return value is a string. It can be plain text or HTML:

@app.route('/')
def index():
    # Return plain text
    return "Hello, Text!"

    # Return HTML (Flask auto-renders HTML tags)
    return "<h1>Hello, <em>HTML</em>!</h1>"

2. Handling HTTP Methods

By default, @app.route only accepts GET requests (for data retrieval). To handle POST requests (for form submissions), explicitly specify methods in the decorator:

from flask import request  # Import request to access request data

@app.route('/login', methods=['GET', 'POST'])  # Allow GET and POST
def login():
    if request.method == 'POST':  # Check request method
        # Process form submission
        username = request.form.get('username')
        return f"Login successful: {username}"
    else:
        # Display login form
        return '''
        <form method="post">
            Username: <input type="text" name="username">
            <button type="submit">Login</button>
        </form>
        '''

3. Returning JSON Data

For API responses, return a dictionary, and Flask automatically converts it to JSON with proper headers:

from flask import jsonify

@app.route('/api/data')
def api_data():
    data = {
        "name": "Flask",
        "version": "2.0",
        "features": ["Lightweight", "Flexible", "Extensible"]
    }
    return jsonify(data)  # Returns JSON response

五、Starting and Debugging

During development, use app.run() to start the Flask server. For debugging, enable debug=True (disable in production to avoid security risks):

if __name__ == '__main__':
    app.run(debug=True)  # Auto-restarts on code changes

The server runs at http://127.0.0.1:5000/ (default port 5000; change with port=8080).

六、Summary

Routes and view functions are the core foundations of Flask. Mastering them allows you to build basic web apps:
1. Routes: Define URL-function mappings with @app.route.
2. Dynamic Routes: Use <parameter> for variable paths and specify types (e.g., <int:id>).
3. View Functions: Process requests and return responses (text, HTML, JSON).
4. HTTP Methods: Specify methods=['GET', 'POST'] to handle different request types.

Practice Suggestion: Create a small project with “Homepage, User Page, Login Page” to experiment with routes and view functions.

By now, you’ve grasped Flask’s routes and view functions. Next, explore templates (rendering HTML files), static files (CSS/JS), and other advanced topics to build more complex web applications!

Xiaoye