python - 耗时 flask 的装饰器

标签 python flask error-logging

尝试记录使用装饰器运行函数所需的时间,但我误解了一些东西。它拒绝写登录装饰器。

当你颠倒装饰器的顺序时,它会导致模板上的构建错误(就像信息丢失一样)。

在我的初始 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/

相关文章:

python - 将列表传递给 pandas 系列作为索引

python - 添加 x-www-form-urlencoded 到 post 请求

python - Python 轮子 (.whl) 是否有 MIME 类型?

python - 将 flask 项目从 python2 更新到 python3

mongodb - 从其他容器访问时,Dockerized Mongodb拒绝连接

javascript - 如何在 JavaScript try catch 中将 native ReferenceError 对象堆栈传递到控制台?

python - 如何使用 Python API 创建新的 Perforce 用户?

javascript - 我需要对 Facebook Connect 脚本错误采取措施吗?

c# - 如何使用 ELMAH 手动记录错误

python - Flask-Migrate 未检测到表格