Flask: Core Concepts and Basic Applications

I. What is Flask?

A web framework is like a “pre-fabricated component” in architecture, helping us quickly build web applications without writing all code from scratch. Flask is a lightweight web framework written in Python with a “micro” design philosophy—lightweight, flexible, and only providing the core functionality. Other complex features can be implemented through extensions.

In simple terms, Flask is like an empty house frame. You can add walls (routes) and doors/windows (features) as needed, while the basic structure is already in place, allowing you to focus on the business logic of your web pages.

II. Why Choose Flask?

  • Lightweight and Flexible: It doesn’t come with many built-in features. You can choose components freely—for example, add an ORM if you want to build a blog, or a login plugin for user authentication.
  • Low Learning Curve: Core concepts are simple, syntax is concise, making it ideal for beginners to start web development.
  • Strongly Extensible: Despite being lightweight, it has rich third-party extensions (e.g., Flask-SQLAlchemy, Flask-Login) to meet complex project requirements.
  • User-Friendly Documentation: The official documentation is clear and easy to understand, and the community is active, so solutions to problems are easy to find.

III. Detailed Explanation of Core Concepts

1. Routes: The Bridge Between URLs and Functions

Routes are like road signs on a map, telling Flask “which URL corresponds to which function.” Define them using the decorator @app.route():

@app.route('/')  # Define the root URL
def index():     # View function to handle the URL request
    return "Hello, Flask!"  # Return page content
  • Decorators: Python decorators are “syntactic sugar.” Adding @app.route('/') to a function tells Flask this function will handle requests for the root path /.
  • Dynamic Route Variables: You can capture URL parameters dynamically, for example, for user pages:
  @app.route('/user/<username>')  # <username> is a dynamic parameter
  def user_profile(username):
      return f"Hello, {username}!"  # Directly use parameters to construct content

2. View Functions: The Core of Request Handling

View functions are the “processing functions” pointed to by routes, responsible for receiving requests, processing data, and returning responses. For example:

@app.route('/greet')
def greet():
    name = "Flask"
    return f"<h1>Hello, {name}!</h1>"  # Return HTML content
  • Return Content: You can return strings directly (including HTML tags), JSON (using jsonify()), or render templates (using render_template()).

3. Requests and Responses

  • Request Object: Obtain data from the client (browser), such as user input forms or URL parameters. Import request:
  from flask import request

  @app.route('/search', methods=['GET', 'POST'])
  def search():
      if request.method == 'POST':  # Check request type (GET/POST)
          keyword = request.form.get('keyword')  # Get form data
          return f"Search keyword: {keyword}"
      else:  # For GET requests
          return "Please enter a keyword"
  • Response Object: Return data to the client. The simplest way is to use return, and you can also customize the status code:
  return "Not Found", 404  # Return a 404 error

4. Templates: Dynamically Generating Pages

Directly returning HTML strings is inflexible. Template engines (Flask uses Jinja2 by default) help render pages more efficiently. Steps:
1. Create a templates folder in the project root (must be named “templates”).
2. Create index.html in templates:

   <!DOCTYPE html>
   <html>
   <body>
       <h1>Hello, {{ name }}!</h1>  <!-- Jinja2 variable rendering -->
       {% if age > 18 %}
           <p>Adult</p>
       {% else %}
           <p>Minor</p>
       {% endif %}
   </body>
   </html>
  1. Render the template in the view function:
   from flask import render_template

   @app.route('/template')
   def use_template():
       data = {
           "name": "Flask",
           "age": 20
       }
       return render_template('index.html', **data)  # Pass data to the template

5. Static Files: CSS, JS, Images, etc.

Static files (e.g., stylesheets, images, JavaScript) are placed in the static folder at the project root. Reference them using url_for('static', filename='xxx'):

<!-- Reference CSS in a template -->
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

<!-- Reference an image -->
<img src="{{ url_for('static', filename='logo.png') }}">

6. Extensions: Enhancing Functionality

Flask itself has simple functionality, but extensions help implement complex requirements quickly:
- Flask-SQLAlchemy: ORM tool for database operations (no need to write raw SQL).
- Flask-Login: Implements user login, logout, and session management.
- Flask-WTF: Handles form validation (e.g., preventing duplicate submissions, data validation).

IV. Basic Application Practice: Building a Simple Website from Scratch

1. Minimal Example: First Flask App

Create an app.py file in the project root:

from flask import Flask

# Initialize Flask app (__name__ is the current module name)
app = Flask(__name__)

# Define routes and view functions
@app.route('/')
def home():
    return "Welcome to Flask Station! <a href='/about'>About Us</a>"

@app.route('/about')
def about():
    return "This is a simple demo website built with Flask."

# Run the app (only when executed directly)
if __name__ == '__main__':
    app.run(debug=True, port=5000)  # debug=True: auto-restart when code changes

Run it: Execute python app.py in the terminal. Open http://localhost:5000 in your browser to see “Welcome to Flask Station!”.

2. Extended Functionality: Adding Templates and Static Files

(1) Project Structure

my_flask_app/
├── app.py          # Main program
├── templates/      # Template folder
│   └── index.html  # Home page template
└── static/         # Static files folder
    └── style.css   # Stylesheet

(2) Modify index.html Template:

<!DOCTYPE html>
<html>
<head>
    <title>Flask Station</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>Hello, Flask!</h1>
    <p class="intro">This is an example of a lightweight web framework.</p>
    <a href="/about">About Us</a>
</body>
</html>

(3) Modify style.css:

body {
    font-family: Arial;
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}
.intro {
    color: #666;
}

(4) Modify app.py:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')  # Render templates/index.html

@app.route('/about')
def about():
    return render_template('about.html')  # Assume about.html is in templates

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

Run app.py again, and you’ll see a styled page with hyperlinks!

V. Summary and Learning Recommendations

Flask’s core advantage is “lightweight + flexible,” suitable for starting with small projects and gradually expanding functionality. Beginners should first master basic concepts like routes, views, templates, and static files, then learn extension tools (e.g., ORM, user authentication).

Recommended Learning Resources:
- Official Documentation: flask.palletsprojects.com
- Quickstart Tutorial: Follow the official “Quickstart” to write examples and learn by doing.
- Practical Project References: Try building a simple blog or to-do list with Flask.

With this article, you’ve learned Flask’s core concepts and basic applications. Next, try modifying the example code—for instance, adding form submissions or dynamic parameter rendering—to quickly master the basics of web development!

Xiaoye