Skip to content

Instantly share code, notes, and snippets.

@ruanbekker
Created January 11, 2021 13:13
Show Gist options
  • Save ruanbekker/09cac44ea534501b5677653b1b7bd436 to your computer and use it in GitHub Desktop.
Save ruanbekker/09cac44ea534501b5677653b1b7bd436 to your computer and use it in GitHub Desktop.
Timing requests with Python Flask
# source: https://opensource.com/article/18/4/metrics-monitoring-and-python
from flask import request
import csv
import time
def start_timer():
request.start_time = time.time()
def stop_timer(response):
# convert this into milliseconds for statsd
resp_time = (time.time() - request.start_time)*1000
with open('metrics.csv', 'a', newline='') as f:
csvwriter = csv.writer(f)
csvwriter.writerow([str(int(time.time())), str(resp_time)])
return response
def setup_metrics(app):
app.before_request(start_timer)
app.after_request(stop_timer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment