gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:35:41 29 4
gpt4 key购买 nike

现在我正在 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com