Created
January 12, 2013 23:49
-
-
Save lost-theory/4521102 to your computer and use it in GitHub Desktop.
flask: show request time in template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from flask import Flask, request, g, render_template | |
app = Flask(__name__) | |
app.config['DEBUG'] = True | |
@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 index(): | |
t = request.values.get('t', 0) | |
time.sleep(float(t)) #just to show it works... | |
return render_template("index.html") | |
if __name__ == "__main__": | |
app.run(use_debugger=True, use_reloader=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rendered in {{ g.request_time() }} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ curl http://127.0.0.1:5000/ | |
Rendered in 0.00100s | |
$ curl http://127.0.0.1:5000/?t=1 | |
Rendered in 1.00106s | |
$ curl http://127.0.0.1:5000/?t=2 | |
Rendered in 2.00111s | |
$ curl http://127.0.0.1:5000/?t=10 | |
Rendered in 10.00057s |
I got jinja2.exceptions.TemplateNotFound
please resolve this
@mallikharjuna160003 To resolve this error just create a directory "templates" and put the required html files in.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You’ll want to use
time.monotonic()
for correctness :)Otherwise, you end up with weird negative page rendering times during leap seconds :)