Flask-SQLAlchemy 实用代码片段

1. 记录慢查询

flask 在 debug 模式下运行时,flask-sqlalchemy 会自动记录所有的 queries,在请求结束前,可以通过 flask_sqlalchemy.get_debug_queries() 获取到所有查询。

在非 debug 模式下,也可以在配置中手动指定 SQLALCHEMY_RECORD_QUERIES=True,使 get_debug_queries 可用。

# 设置配置变量
app.config['DATABASE_QUERY_TIMEOUT'] = 0.001
app.config['SQLALCHEMY_RECORD_QUERIES'] = True

# 省略若干字

# 在请求结束时,记录慢查询
@app.after_request
def after_request(response):
    for query in get_debug_queries():
        if query.duration >= app.config['DATABASE_QUERY_TIMEOUT']:  # 用时判断
            app.logger.warning(
                ('\nContext:{}\nSLOW QUERY: {}\nParameters: {}\n'
                 'Duration: {}\n').format(query.context, query.statement,
                                          query.parameters, query.duration))
    return response

当然,也可以直接设置 SQLALCHEMY_ECHO=True,这对应 SQLAlchemy 的 create_engine(..., echo=True),会打印出生成的所有 SQL 语句(通过 logging)

posted @ 2019-03-09 12:23  於清樂  阅读(831)  评论(0编辑  收藏  举报