Published on

Understanding Flask's `@app.route` decorator

Authors
  • avatar
    Name
    hwahyeon
    Twitter
@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route is a Flask decorator used to map a URL to a Flask function (view function). In the code above, when the / URL is requested, Flask uses WSGI to map it to the hello_world() function and executes it.

What is a Decorator?

A decorator is a Python feature that acts like "wrapping paper" for a function, adding extra functionality. It keeps the original function intact while allowing additional actions to be performed before or after the function is executed.

Simple Example:

def add_wrapper(func):
    def wrapper():
        print("1")
        func()  # Executes the original function
        print("3")
    return wrapper

@add_wrapper
def greet():
    print("2")

When greet() is executed, the output is:

1
2
3

Here, @add_wrapper acts as a decorator, adding functionality around the greet() function.

How Is Flask's @app.route Different from Traditional Decorators?

The @app.route decorator in Flask has a slightly different focus compared to traditional decorators:

  • Traditional decorators add functionality before or after a function is executed.
  • In contrast, @app.route only registers the function to a specific URL within Flask.

How Flask's @app.route Works

  1. Registration Stage The @app.route decorator links a URL (e.g., /) to a function in Flask.

  2. Request Handling Stage When the browser sends a request to /:

    • Flask uses WSGI to handle the request and checks the routing table to find the associated function.
    • It then calls the function to generate the response.