4

デコレータを使用して関数の実行にかかる時間を記録しようとしていますが、何か誤解しています。デコレータにログインするための書き込みを拒否します。

デコレータの順序を逆にすると、テンプレートでビルド エラーが発生します (情報が失われたかのように)。

私のinit pyで:

if app.debug is not True:   
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler('python.log', maxBytes=1024 * 1024 * 100, backupCount=20)
    file_handler.setLevel(logging.ERROR)
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)

私のviews.pyで:

def print_elapsed_time(func):
        from time import clock
        def wrapper(**kwargs):
            tic = clock()
            result = func(**kwargs) # this function fails to log the error below
            app.logger.error("\tElapsed time for function: %.1f s" % (clock() - tic))
            return result
        return wrapper


@print_elapsed_time
@app.route('/index', methods=['GET','POST'])
@app.route('/index/<int:page>', methods=['GET','POST'])
def ListPosts(page = 1):    
    app.logger.error("got user") # works
    # posts = query
    return render_template('index.html', post=posts)
4

2 に答える 2

1

print_elapsed_timeFlask のデコレーターの上のデコレーターでは、デコレーターは下から上に適用されるため、routeによって登録された関数は によってrouteまだ変更されていません。解決策は、両方のデコレータの下print_elapsed_timeに置くことです。ただし、Flask は登録された関数をその名前で追跡し、これでラップされたすべての関数はです。それを回避する方法については、別の StackOverflow の質問に対する私の回答を参照してください。@print_elapsed_timerouteprint_elapsed_timewrapper

于 2013-08-26T21:21:42.633 に答える