Calculate execution time for every page in Python's Flask


Question

What's a good way to calculate the execution time for every page load using Python's Flask library?

I was thinking of putting a start timer in views/__ init__.py:

@app.before_request
def before_request():
  g.start = time.time()

But where would I put the end part of the timer to calculate the difference, and how would I get it into the footer of my html template?

Thanks.

1
15
9/5/2012 2:51:17 AM

Put it in teardown_request function:

@app.teardown_request
def teardown_request(exception=None):
    diff = time.time() - g.start
    ...

In teardown_request you are not allowed to change the response, If you want to use the calculated string in your response use after_request:

@app.after_request
def after_request(response):
    diff = time.time() - g.start
    if (response.response):
        response.response[0] = response.response[0].replace('__EXECUTION_TIME__', str(diff))
    return response
15
10/4/2012 2:12:20 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon