20

使用 Python 的 Flask 库计算每个页面加载的执行时间的好方法是什么?

我正在考虑在 views/__ init__.py 中放置一个启动计时器:

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

但是我会将计时器的末尾部分放在哪里来计算差异,以及如何将它放入我的 html 模板的页脚中?

谢谢。

4

6 回答 6

16

把它放在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
于 2012-09-05T03:08:03.923 回答
14

其他答案基本上是正确的,但现在已经过时了。

以下适用于 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 将正确更新内容长度。另请注意字节字符串的使用和编码。

于 2018-08-16T10:15:38.110 回答
3

您还需要更新 content-length 标头,否则浏览器会感到不安(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
于 2012-10-23T15:33:24.177 回答
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
于 2013-03-04T14:55:49.220 回答
1

试试这个: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>
于 2021-04-13T04:52:55.873 回答
-1

这个 elapsed 属性在这里怎么样?

这是解决方案

>>> import requests
>>> r = requests.get('https://google.com')
>>> r.elapsed.total_seconds()
0.216452
>>> r.elapsed.seconds
0
>>> r.elapsed.microseconds
216452
于 2021-03-31T15:04:07.207 回答