Python Flask: execute code before every request

Flask before_request

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.

examples/flask/before_request/app.py

from flask import Flask

app = Flask(__name__)

@app.before_request
def before_request():
    app.logger.info("before_request")


@app.route("/")
def main():
    app.logger.info("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
127.0.0.1 - - [22/Jun/2020 23:24:56] "GET / HTTP/1.1" 200 -

Related Pages

Flask Tutorial

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Python Maven web site.

Gabor Szabo