Zach Siegel
Zach Siegel

Reputation: 370

When does Flask's route decorator execute?

When is decorator in Flask's route method executed? Specifically, I want to know when self.add_url_rule() is executed.

from flask import Flask
app = Flask(__name__)
@app.route("/")
def root_of_app():
    load_root_of_app()

Is add_url_rule executed when the module containing root_of_app is first imported, or when root_of_app is first called by a web request?

Here is the source for the route function:

def route(self, rule, **options):
    def decorator(f):
        endpoint = options.pop('endpoint', None)
        self.add_url_rule(rule, endpoint, f, **options)
        return f
    return decorator

Upvotes: 3

Views: 403

Answers (1)

davidism
davidism

Reputation: 127240

You can verify this yourself by adding print statements to the route decorator.

When route is called, it builds a decorator. That decorator is then applied to the view by calling it. Both these happen at import, because importing executes module-level code.

Using @app.route() registers the view, it is not deferred until the first request. The blueprint version of route is deferred until the blueprint is registered on the app, which also happens before the first request.

Upvotes: 3

Related Questions