Sometime there is some code that you would like to run at the beginning of every request. Insead of insert the same code everywhere or event just inserting a function call in every route handler, Flask has an easy way to accomplish this using the before_request hook.


from flask import Flask

app = Flask(__name__)

def before_request():"before_request")

def main():"main route")
    return "Hello World!"

Run as:

FLASK_APP=app FLASK_DEBUG=1 flask run

Output on the console:

[2020-06-22 23:24:56,675] INFO in app: before_request
[2020-06-22 23:24:56,675] INFO in app: main route - - [22/Jun/2020 23:24:56] "GET / HTTP/1.1" 200 -