Flask 学习 十五 性能

记录影响性能的数据库查询

app/main/views.py 

from flask_sqlalchemy import get_debug_queries

@main.after_app_request
def after_request(response):
    for query in get_debug_queries():
        # statement SQL语句;parameters SQL使用的参数;duration 耗时;context 查询源码中所处位置的字符串
        if query.duration >= current_app.config['FLASK_SLOW_DB_QUERY_TIME']:
            current_app.logger.waring('Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n' % (
                query.statement, query.parameters, query.duration, query.context))
    return response

config.py 启用缓慢查询记录功能的配置

    FLASK_SLOW_DB_QUERY_TIME=0.5
    SQLALCHEMY_RECORD_QUERIES=True # 启用缓慢查询记录功能的配置-启用记录查询统计数据的功能

分析源码

manage.py 在请求分析器的监视下运行

@manager.command
def profile(length=25, profile_dir=None):
    '''启动请求分析器'''
    from werkzeug.contrib.profiler import ProfilerMiddleware
    app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir)
    app.run()

使用python manage.py profile 启动程序,终端会显示每条请求的分析数据,其中包含了25个运行最慢的25个函数

--length 可修改函数显示数量

--profile_dir 可保存在指定目录下的文件中

 

posted @ 2017-06-10 12:49  Erick-LONG  阅读(455)  评论(0编辑  收藏  举报