簡體   English   中英

如何在 Flask 的路線中跟蹤每個 function 所用的時間?

[英]How to track the time taken for each function in a route in Flask?

現在我正在嘗試捕獲 flask 中每個請求的統計信息,我能夠捕獲完成請求所需的時間。 有沒有辦法捕獲路線內每個 function 所花費的時間。

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 秒?

一種方法是在您希望計時的函數周圍使用裝飾器。 然后,裝飾器會將 function 的名稱和timings的運行時間添加到保存在應用程序全局g屬性中的字典中。 這可以記錄在teardown_requestafter_request鈎子中,或者像這里所做的那樣,通過/視圖 function 記錄:

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')

更新

I just want to make the point that when you time a view function, the timing will not be created and added to the timings dictionary until after the function returns, so in that case the timings dictionary is best processed in an after_request hook function, for例子:

@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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM