1. What is Flask?

Flask is a lightweight web framework written in Python. It is simple, easy to use, and flexible, making it ideal for beginners to quickly develop web applications. Unlike more complex frameworks (such as Django), Flask emphasizes “extensibility on demand”—you don’t need to preconfigure a large number of components to quickly implement a simple webpage.

2. Installing Flask

Before starting, ensure Python (recommended Python 3.6+) is installed on your computer. Open your terminal (Command Prompt for Windows, Terminal for Mac/Linux) and run:

pip install flask

If you encounter permission issues, try pip3 install flask (for Python 3). After installation, verify with:

flask --version

3. First Flask Application: Routing & View Functions

A “route” acts as the “entry point” for a webpage. For example, when accessing http://localhost:5000/, Flask needs to know which “handler function” (view function) to execute. A “view function” processes the request and returns content.

3.1 Writing Basic Code

Create a new Python file (e.g., app.py) and add:

# Import the Flask class
from flask import Flask

# Initialize the Flask application; 'app' is the application object
app = Flask(__name__)

# Define a route: When the root path '/' is accessed, the following function is executed
@app.route('/')
def home():
    # The string returned by the function is automatically sent as webpage content to the user
    return "Hello, Flask!"

# Run the application (only when the script is executed directly)
if __name__ == '__main__':
    app.run()

3.2 Code Explanation

  • Import Flask: from flask import Flask accesses Flask’s web development features.
  • Initialize app: app = Flask(__name__) creates a Flask application object. __name__ is a Python built-in variable representing the current module name (used to locate resource paths).
  • Route Decorator: @app.route('/') is critical—it “binds” the route path (here, the root path /) to the home function. When http://localhost:5000/ is accessed, Flask automatically calls home().
  • View Function: The home() function is the core handler. Its return value (e.g., the string “Hello, Flask!”) is automatically converted by Flask into an HTTP response and displayed in the browser.
  • Run the App: app.run() starts Flask’s built-in development server, defaulting to port 5000 with the address http://127.0.0.1:5000.

3.3 Run the App and Visit

Execute python app.py in the terminal (ensure you’re in the directory with app.py). You’ll see output like:

 * Serving Flask app 'app'
 * Running on http://127.0.0.1:5000 (Press CTRL+C to quit)

Open your browser and visit http://localhost:5000—you’ll see “Hello, Flask!”! Congratulations on your first Flask page!

4. Advanced: Dynamic Routes (Parameterized Pages)

Flask supports dynamic routes for flexible content. For example, accessing /user/Alice can display “Hello, Alice!”.

Modify app.py:

from flask import Flask
app = Flask(__name__)

# Basic route (root path)
@app.route('/')
def home():
    return "Hello, Flask!"

# Dynamic route: <username> is a placeholder for the parameter
@app.route('/user/<username>')
def user_profile(username):
    return f"Hello, {username}!"

if __name__ == '__main__':
    app.run()

Now:
- Access http://localhost:5000/user/Alice → “Hello, Alice!”
- Access http://localhost:5000/user/Bob → “Hello, Bob!”

Tip: Dynamic routes support type-specific parameters:
- <int:num>: Accepts integers (e.g., /user/123num=123).
- <float:price>: Accepts floats.
- Default: String type.

5. Summary

  1. Installation:
   pip install flask
  1. Core Concepts:
    - Routing: Bind URLs to view functions with @app.route(URL).
    - View Functions: Process requests and return content.
    - Run App: app.run() starts the development server.
  2. Key Tips:
    - Use if __name__ == '__main__' to ensure app.run() only runs when the script is executed directly.
    - Dynamic routes use <param> to pass variables for flexible pages.

Try modifying the code:
- Change the route (e.g., /about) for different content.
- Return HTML tags (e.g., <h1>Hello</h1>) in view functions for styled pages.

Explore Flask’s rich features and start building!

Xiaoye