Python Flask: execute code once before first request

Flask before_first_request

Sometimes you would like to have code that will be executed once, before ant user arrives to your site, before the first request arrives. You could put some code in the body of your Flask application file, that code will execute when the application launches. Alternatively, and in many case in a cleaner way you could use the before_first_request hook.

examples/flask/before_first_request/app.py

from flask import Flask

app = Flask(__name__)

@app.before_first_request
def before_first_request():
    app.logger.info("before_first_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_first_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