'In Flask framework @app.route('/') , how route('/') function is used as a decorator from app object? [closed]

In the Flask framework, app is an object and route('/') is a function which is used as a decorator. Can anybody tell me what the mechanism behind this decorator? How is the route('/') method is called?

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'


Solution 1:[1]

The variable app has no direct relation to the file app.py. You could name both of them differently.

app.route('/') is a function call that returns a decorator, which then is applied to hello_world.

You could write

@app.route('/')
def hello_world():
    return 'Hello, World!'

as

root_decorator = app.route('/')

@root_decorator
def hello_world():
    return 'Hello, World!'

or as

root_decorator = app.route('/')

def hello_world():
    return 'Hello, World!'

hello_world = root_decorator(hello_world)

Here's a mock of what happens:

class Flask:
    def route(self, path):
        def decorator(function):
            def new_function(*args, **kwargs):
                print(f'path is {path!r}. doing some Flask magic now.')
                return function(*args, **kwargs)
            return new_function
        return decorator

app = Flask()

@app.route('/')
def hello_world():
    return 'Hello, World!'

Demo:

>>> result = hello_world()
path is '/'. doing some Flask magic now.
>>> result
'Hello, World!'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 timgeb