- Published on
Understanding Flask's `@app.route` decorator
- Authors

- Name
- hwahyeon
@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.routeonly registers the function to a specific URL within Flask.
How Flask's @app.route Works
Registration Stage The
@app.routedecorator links a URL (e.g.,/) to a function in Flask.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.