python - 如何跟踪 Flask 中 route 每个函数所花费的时间?

标签 python python-2.7 flask logging

现在我正在 try catch flask 中每个请求的统计信息,我能够捕获请求完成所需的时间。有没有办法捕获路线内每个功能所花费的时间。

MY Code capturing the time taken by a route
@app.teardown_request
def teardown_func(response):
    print("tearing down reqest")
    print("Request",request)
    required_data = {
        "path": request.full_path,
        "url": request.url,
        "json_data": request.get_json(),
        "start": request.start_time,
        "stop": dt.utcnow(),
        "total_elapsed_time": (dt.utcnow() - request.start_time).total_seconds()
    }
    print("request data",required_data)
    return response

def call_func():
    sleep(5)
    print("FunctionCalled")

def another_func():
    sleep(5)
    print("FunctionCalled2")


@app.route('/',methods=['GET','POST'])
def hello2():
    time.sleep(10)
    call_func()
    another_func()
    return 'Hello World'

如何计算 call_func() 和 another_func() 在执行该路由时花费了 5 秒的时间?

最佳答案

一种方法是在您想要计时的函数周围使用装饰器。然后,装饰器会将函数名称以及函数运行时间添加到保存在应用程序全局 g 属性 timings 中的字典中。这可以记录在 teardown_requestafter_request Hook 中,或者如此处所示,通过 / View 函数记录:

from flask import Flask, Response, g
import time

app = Flask(__name__)

@app.before_request
def before_request_func():
    g.timings = {}

from functools import wraps
def time_this(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        r = func(*args, **kwargs)
        end = time.time()
        g.timings[func.__name__] = end - start
        return r
    return wrapper


@time_this
def call_func():
    time.sleep(1)

@time_this
def another_func():
    time.sleep(2)

@app.route('/',methods=['GET','POST'])
def hello2():
    call_func()
    another_func()
    return Response('Hello World: ' + str(g.timings), mimetype='text/plain')

更新

我只是想指出一点,当您为 View 函数计时时,直到函数返回后才会创建计时并将其添加到 timings 字典中,因此在这种情况下 timings 字典最好在 after_request 钩子(Hook)函数中处理,例如:

@app.after_request
def after_request_func(response):
    # just append timings to the output response:
    response.data += ('\n' + str(g.timings)).encode('ascii')
    return response

@app.route('/',methods=['GET','POST'])
@time_this
def hello2():
    call_func()
    another_func()
    return Response('Hello World', mimetype='text/plain')

输出:

Hello World
{'call_func': 1.0014231204986572, 'another_func': 2.0004665851593018, 'hello2': 3.001889705657959}

关于python - 如何跟踪 Flask 中 route 每个函数所花费的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61060941/

相关文章:

python - 将数据帧返回函数应用于基础数据帧的每一行

python - opencv 中的 SIFT() 不工作 : 'module' object has no attribute 'SURF'

python - curl 如何 POST multipart/form-data 数据以及如何读取 flask 请求中的 multipart/form-data

python - 如何使用 Python 在 WebDriver 中发送多个 key ?

python - 写入文本文件被切断

python - 如何在 flask 中获取http header ?

python - 如何使用 Python 和 OpenCV 增强图像然后将其转换为二进制图像?

python - 对不同大小的 bool 数组进行或运算

python - 如何在 jinja2 模板中显示日期时间字段? ( flask )

flask - jinja2.exceptions.UndefinedError : 'str object' has no attribute 'username'