Measuring Execution Time of Flask App Endpoint Feb 8th 2021 Words: 127

Problem

I have construct an REST API using flask, a lightweight WSGI web application framework. However, during the testing, some endpoints takes seconds to response. It may be a result of bad code, or just a network jitter. Therefor, I need to measuring the time elapse from the moment a request come in, to the point where the response is sent.

Solution

Flask (1.1.x) does not have a timestamp in the request object, thus the timestamp must be recorded manually. The global context ‘g’ provided by flask do the job well.

1
2
3
4
5
6
7
8
9
10
11
12
13
from flask import g

# Before each request
@app.before_request
def before_request():
g.start_time = time.time()

# After request handler
@app.after_request
def after_request(response):
logger.debug(f"Time used: {time.time() - g.start_time}")
return response