尝试记录使用装饰器运行函数所需的时间,但我误解了一些东西。它拒绝写登录装饰器。
当你颠倒装饰器的顺序时,它会导致模板上的构建错误(就像信息丢失一样)。
在我的初始 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)
最佳答案
随着 print_elapsed_time
Flask 上方的装饰器 route
装饰器,由 route
注册的函数尚未被 print_elapsed_time
修改,因为装饰器是从下到上应用的。解决办法是把@print_elapsed_time
低于route
装饰器。但是,Flask 通过它们的名称 跟踪其注册的函数,并跟踪由 print_elapsed_time
包装的所有内容这是wrapper
.看我的回答to another StackOverflow question寻找解决方法。
关于python - 耗时 flask 的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452559/