In some applications it is a nice idea to show how long it took to load a page. Using the g global object and attaching a function call to it, we can do this fairly close to the real value, without needing to add a lot of extra code to every route just by using the before_request decorator.

examples/flask/elapsed_time/app.py

import time
from flask import Flask, request, render_template, g
app = Flask(__name__)


@app.before_request
def before_request():
   g.request_start_time = time.time()
   g.request_time = lambda: "%.5fs" % (time.time() - g.request_start_time)


@app.route("/")
def main():
    return render_template('main.html')

examples/flask/elapsed_time/templates/main.html

<html>
<head>
</head>
<body>
<h1>Show elapsed time</h1>

<hr>
Elapsed time: {{ g.request_time() }}
</body>
</html>


Start the application with this command:

FLASK_APP=app FLASK_DEBUG=1 flask run --host 0.0.0.0 --port 5000

See the Flask API for more explanation.