Python Web Development: A Quick Start with the Lightweight Flask Framework

1. What is Flask?

Before diving in, let’s understand what a “Web framework” is. Simply put, a Web framework is a collection of tools that helps you quickly develop websites or web applications. It encapsulates repetitive tasks (like handling HTTP requests, routing, template rendering, etc.), allowing you to focus on your business logic.

Flask is a lightweight Python Web framework developed by Armin Ronacher. Its key features include:

  • Lightweight and Flexible: No mandatory project structure or components—you can add functionality as needed.
  • Low Learning Curve: Simple syntax, ideal for beginners to get started quickly.
  • Strongly Extensible: Can achieve complex features through extensions (e.g., Flask-SQLAlchemy for database operations, Flask-Login for user authentication).

If you want to quickly build a small website, API endpoints, or use it as a starting point for learning web development, Flask is an excellent choice.

2. Environment Setup

Installing Flask

First, ensure Python is installed on your computer (Python 3.6+ is recommended). Open your command line and run:

pip install flask

After installation, verify it with:

flask --version

If you see output like Flask 2.3.3, Python 3.9.7, the installation was successful.

3. Your First Flask Application

Writing “Hello World”

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

from flask import Flask

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

# Define a route: When accessing the root path '/', execute the following function
@app.route('/')
def index():
    return "Hello, Flask!"  # Return response content

# Start the application (only when the file is run directly)
if __name__ == '__main__':
    app.run(debug=True)  # debug=True enables debug mode (use during development, disable in production)

Running the Application

Navigate to the directory containing app.py in the command line and run:

python app.py

Then open your browser and visit http://127.0.0.1:5000. You’ll see the message Hello, Flask!.

Code Explanation

  • Flask(__name__): Creates the application instance. __name__ is a Python built-in variable representing the current module’s name. Flask uses this to locate resource paths.
  • @app.route('/'): Route Decorator that binds the URL path / to the function index(). When a user visits /, the index() function is automatically executed.
  • app.run(debug=True): Starts the Flask development server. debug=True automatically restarts the server after code changes and displays error messages (disable in production).

4. Routing and View Functions

Basic Routing

Routing is the mapping between URLs and functions. Besides the root path /, you can define other paths:

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

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

Visiting http://127.0.0.1:5000/user/ZhangSan will display Welcome to ZhangSan's profile page.

Route Parameter Types

Flask supports various parameter types (integer, float, path, etc.):

@app.route('/post/<int:post_id>')  # post_id must be an integer
def show_post(post_id):
    return f"The article ID you're viewing is: {post_id}"

@app.route('/path/<path:subpath>')  # Path with slashes
def show_path(subpath):
    return f"Path parameter: {subpath}"

5. Template Engine (Jinja2)

Static HTML pages can’t handle dynamic content. Flask uses the Jinja2 template engine to render dynamic HTML.

Creating Template Files

  1. Create a templates folder in your project root (Flask will automatically recognize this folder).
  2. Inside templates, create index.html with:
<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>  <!-- Render variables -->
</head>
<body>
    <h1>Hello, {{ name }}!</h1>  <!-- Render the 'name' variable -->
    {% if age > 18 %}  <!-- Conditional statement -->
        <p>You are an adult</p>
    {% else %}
        <p>You are a minor</p>
    {% endif %}
    <ul>
        {% for item in hobbies %}  <!-- Loop -->
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
</body>
</html>

Rendering Templates in View Functions

Modify app.py to use render_template:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    # Data passed to the template
    data = {
        'title': 'Home',
        'name': 'Xiaoming',
        'age': 20,
        'hobbies': ['Coding', 'Reading', 'Sports']
    }
    return render_template('index.html', **data)  # **data unpacks the dictionary

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

Now, when you visit http://127.0.0.1:5000, the page will dynamically render content based on the passed variables.

6. Static File Handling

Static resources like images, CSS, and JavaScript should be placed in the static folder.

Example: Including a CSS File

  1. Create a static folder in your project root, then add style.css inside it:
h1 {
    color: red;
    font-size: 24px;
}
  1. In templates/index.html, include the CSS:
<head>
    <title>{{ title }}</title>
    <!-- Import static files: url_for('static', filename='style.css') -->
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>

The page title will now appear in red, indicating the CSS is working.

7. Handling Requests and Responses

Getting Request Parameters

Flask uses the request object to access request data (import it first):

from flask import request, render_template

@app.route('/greet', methods=['GET', 'POST'])  # Allow GET and POST requests
def greet():
    if request.method == 'POST':  # Check request method
        name = request.form.get('name')  # Get POST form data
        return render_template('greet.html', name=name)
    else:
        return render_template('greet.html')  # Return empty form for GET requests

Returning JSON and Redirects

  • Returning JSON: Use jsonify (import it first):
from flask import jsonify

@app.route('/api/data')
def api_data():
    data = {'name': 'Flask', 'version': '2.3.3'}
    return jsonify(data)  # Return JSON-formatted data
  • Redirecting: Use redirect (import it first):
from flask import redirect, url_for

@app.route('/old')
def old_page():
    return redirect(url_for('index'))  # Redirect to the index page

8. Comprehensive Small Project Example

Let’s build a simple “Personal Blog Homepage” with:
- Displaying welcome messages and user lists
- Supporting user message submissions (POST requests)
- Rendering dynamic content (using templates)

Step 1: Modify Template Structure

Create templates/blog.html:

<!DOCTYPE html>
<html>
<head>
    <title>My Blog</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>{{ blog_title }}</h1>
    <h2>User List</h2>
    <ul>
        {% for user in users %}
            <li>{{ user }}</li>
        {% endfor %}
    </ul>

    {% if message %}  <!-- Display message -->
        <div class="message">{{ message }}</div>
    {% endif %}

    <form method="POST">
        <input type="text" name="username" placeholder="Enter username">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Step 2: Write View Functions

Update app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/blog', methods=['GET', 'POST'])
def blog():
    users = ['Zhang San', 'Li Si', 'Wang Wu']  # Simulated user list
    message = None  # Message content

    if request.method == 'POST':
        username = request.form.get('username')
        message = f"Received message: {username} submitted information!"

    return render_template('blog.html', 
                          blog_title='Personal Blog', 
                          users=users, 
                          message=message)

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

Demo

Visit http://127.0.0.1:5000/blog to see the user list and submit messages (messages will dynamically appear on the page).

9. Summary and Advanced Directions

Congratulations on completing the Flask basics! You now know:
- Flask installation and basic usage
- Routing, view functions, and template rendering
- Static files and the template engine
- Handling request parameters and returning responses

Future Learning Paths:

  • Database Operations: Learn Flask-SQLAlchemy (ORM tool)
  • User Authentication: Use Flask-Login for login/registration
  • RESTful APIs: Build APIs with Flask-RESTful
  • Deployment: Deploy to production using Gunicorn + Nginx

The official Flask documentation (https://flask.palletsprojects.com/) is the best resource. Practice is key to mastering it!

Xiaoye