使用Python的Flask库计算每个页面加载的执行时间有什么好方法?
我正在考虑在views / __ init __。py:
中放置一个启动计时器@app.before_request
def before_request():
g.start = time.time()
但是我会在哪里放置计时器的末尾部分来计算差异,以及如何将它放入我的html模板的页脚?
感谢。
答案 0 :(得分:15)
将其放入teardown_request
函数:
@app.teardown_request
def teardown_request(exception=None):
diff = time.time() - g.start
...
在teardown_request
中,您无权更改回复,如果您想在回复中使用计算字符串,请使用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
答案 1 :(得分:4)
其他答案基本上是正确的,但现在已经过时了。
以下适用于Python 3.6 / 3.7和Flask 1.0.2:
import time
from flask import g
@app.before_request
def before_request():
g.start = time.time()
@app.after_request
def after_request(response):
diff = time.time() - g.start
if ((response.response) and
(200 <= response.status_code < 300) and
(response.content_type.startswith('text/html'))):
response.set_data(response.get_data().replace(
b'__EXECUTION_TIME__', bytes(str(diff), 'utf-8')))
return response
通过使用response.set_data
,Flask将正确更新内容长度。还请注意字节字符串和编码的使用。
答案 2 :(得分:2)
您还需要更新内容长度标题,否则浏览器会感到不安(Chrome似乎会产生不可预测的结果)。
@app.after_request
def after_request(response):
diff = time.time() - g.start
if app.debug:
print "Exec time: %s" % str(diff)
if (response.response):
response.response[0] = response.response[0].replace('__EXECUTION_TIME__', str(diff))
response.headers["content-length"] = len(response.response[0])
return response
答案 3 :(得分:1)
我用Peter Farmer的答案提供静态文件的“破管错误”,以及重定向问题(HTTP 301),所以我调整了提供的代码,如果有帮助的话。
@app.after_request
def after_request(response):
diff = int((time.time() - g.start) * 1000) # to get a time in ms
if (response.response and response.content_type.startswith("text/html") and response.status_code==200):
response.response[0] = response.response[0].replace('__EXECUTION_TIME__', str(diff))
return response
答案 4 :(得分:0)
this elapsed attribute here 怎么样?
这是解决方案
>>> import requests
>>> r = requests.get('https://google.com')
>>> r.elapsed.total_seconds()
0.216452
>>> r.elapsed.seconds
0
>>> r.elapsed.microseconds
216452
答案 5 :(得分:0)
试试这个:https://code-maven.com/flask-display-elapsed-time
import time
from flask import Flask, request, render_template, g
app = Flask(__name__)
@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 main():
return render_template('main.html')
和模板 html 一样:
<html>
<head>
</head>
<body>
<h1>Show elapsed time</h1>
<hr>
Elapsed time: {{ g.request_time() }}
</body>
</html>