Flask SQLAlchemy display queries for debug

后端 未结 8 1219
感情败类
感情败类 2021-02-03 17:21

I am developing an app with flask and SQL Alchemy. I need to display the queries executed to generate a page alongside the time each query took for debugging

What\'s the

8条回答
  •  离开以前
    2021-02-03 18:04

    I'm not sure about generating a webpage out of it, but one good way to debug/log DB queries is to use SQLAlchemy's get_debug_queries().

    ## in app/main/views.py . (my app's main endpoint file)
    from flask import current_app
    from flask_sqlalchemy import get_debug_queries
    
    @main.after_app_request
    def after_request(response):
        for query in get_debug_queries():
            if query.duration >= current_app.config['FLASKY_SLOW_DB_QUERY_TIME']:
                current_app.logger.warning(
                    'Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n'
                    % (query.statement, query.parameters, query.duration,
                       query.context))
        return response
    

    A lot of things are happening here, let's break it down:

    • The @after_app_request decorator ensures this function is called right before the request closes.
    • The function takes in flask's response object, and iterates through the return of get_debug_queries(), which returns a list.
    • It checks each one of these for its duration, and compares it to a predefined config variable (I set mine to 0.5, in seconds).
    • Lastly, it logs the Query along with its properties to the standard flask logger object (Where this gets logged depends on your app configuration).

    Don't forget to set the config variables in your config.py Config class:

    SQLALCHEMY_RECORD_QUERIES = True

    FLASKY_SLOW_DB_QUERY_TIME = 0.5

提交回复
热议问题