【问题标题】:How to track the time taken for each function in a route in Flask?如何在 Flask 中跟踪路线中每个功能所花费的时间?
【发布时间】:2020-07-18 12:26:47
【问题描述】:

现在我正在尝试捕获烧瓶中每个请求的统计信息,我能够捕获完成请求所花费的时间。有没有办法捕捉路线内每个功能所花费的时间。

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

【问题讨论】:

    标签: python python-2.7 flask logging


    【解决方案1】:

    一种方法是在您希望计时的函数周围使用装饰器。然后装饰器会将函数的名称和函数的运行时间添加到保存在应用程序全局g 属性timings 中的字典中。这可以记录在teardown_requestafter_request 钩子中,或者像这里所做的那样,通过/ 视图函数:

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

    更新

    我只想指出,当您对视图函数进行计时时,在函数返回之前不会创建计时并将其添加到 timings 字典中,因此在这种情况下最好处理 timings 字典在 after_request 钩子函数中,例如:

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

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多