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.


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

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

def main():
    return render_template('main.html')


<h1>Show elapsed time</h1>

Elapsed time: {{ g.request_time() }}

Start the application with this command:

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

See the Flask API for more explanation.