Flask-DebugToolbar

repository·main·Indexed 21 days ago

https://github.com/pallets-eco/flask-debugtoolbar

A Flask extension that provides a configurable sidebar of debugging information injected into rendered HTML pages. A port of the django-debug-toolbar, it includes built-in panels for inspecting HTTP headers, request variables, Flask configuration, templates, SQLAlchemy queries, and profiling data. It requires a SECRET_KEY and is automatically enabled when the application is running in debug mode.

Tokens
6.5K
Snippets
20
Records
31
Agent score
72%

What's inside Flask-DebugToolbar

  1. Use built-in Flask-DebugToolbar panels

    main

    Flask-DebugToolbar includes several built-in panels that provide debugging information via the toolbar interface. These panels are automatically available when the toolbar is configured.

    Key built-in panels include:

    • Versions: Shows the installed Flask version and all installed packages/versions via setuptools.
    • Time: Shows request processing time, including CPU time (user/system), wall clock time, and context switches.
    • HTTP Headers: Displays HTTP headers for the current request.
    • Request Vars: Displays view function parameters, cookies, session variables, and GET/POST variables.
    • Config: Shows the contents of app.config.
    • Templates: Shows rendered templates and their provided parameters.
    • SQLAlchemy: Shows SQL queries executed during the request.
    • Logging: Displays log messages recorded during the request.
    • Route List: Displays Flask URL routing rules.
    • Profiler: Reports profiling data for the request (disabled by default).
  2. Basic setup of Flask-DebugToolbar

    main

    To use the toolbar in a standard Flask application, ensure app.debug is set to True and a SECRET_KEY is configured in your app settings. The toolbar is automatically injected into HTML responses when debug mode is active.

    from flask import Flask
    from flask_debugtoolbar import DebugToolbarExtension
    
    app = Flask(__name__)
    
    # the toolbar is only enabled in debug mode:
    app.debug = True
    
    # set a 'SECRET_KEY' to enable the Flask session cookies
    app.config['SECRET_KEY'] = '<replace with a secret key>'
    
    toolbar = DebugToolbarExtension(app)
  3. Configure SQLAlchemy debugging panel

    main

    To use the SQLAlchemyDebugPanel to view SQL queries run during a request, you must use the Flask-SQLAlchemy extension.

    Requirements:

    • The Flask-SQLAlchemy extension must be configured in your application.
    • For SQL syntax highlighting within the panel, you must have Pygments installed in your environment.

    Panel Class: flask_debugtoolbar.panels.sqlalchemy.SQLAlchemyDebugPanel

  4. Install and set up Flask-DebugToolbar

    main

    To use Flask-DebugToolbar, initialize the DebugToolbarExtension with your Flask application instance. You must also ensure that a SECRET_KEY is configured in your app's configuration, as the toolbar requires it. The toolbar is automatically injected into your Jinja templates when the Flask application is running in debug mode.

    from flask import Flask
    from flask_debugtoolbar import DebugToolbarExtension
    
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "<replace with a secret key>"
    
    toolbar = DebugToolbarExtension(app)
  5. Use the Profiler panel

    main

    The ProfilerDebugPanel reports profiling data for the current request.

    Note: Profiling is disabled by default due to the performance overhead it introduces.

    To enable profiling:

    1. Locate the Profiler panel in the toolbar.
    2. Click the checkmark icon to toggle profiling on.
    3. Refresh the page to re-run the request with profiling enabled.
  6. Setup Flask-DebugToolbar with the App Factory pattern

    main

    If you use the Flask app factory pattern, instantiate the DebugToolbarExtension without an app first, then call init_app(app) after your application instance has been created.

    toolbar = DebugToolbarExtension()
    # Then later on.
    app = create_app('the-config.cfg')
    toolbar.init_app(app)
  7. How debug panels are initialized and activated

    main

    Debug panels are managed through a lifecycle that involves both application-level initialization and request-level instantiation:

    1. Application Initialization: During setup, DebugToolbar.load_panels(app) is called, which iterates through the paths in DEBUG_TB_PANELS and executes panel_class.init_app(app) for each.
    2. Request-level Instantiation: For every request, a DebugToolbar instance is created. It iterates through the loaded panel classes and creates instances of them.
    3. Activation via Cookies: Panels can be toggled on or off individually. The toolbar checks the fldt_active cookie. If a panel's dom_id() is present in the unquoted, semicolon-separated list within the fldt_active cookie, that panel instance is marked as is_active = True.
  8. Inspect log messages via the Logging panel

    main

    The LoggingPanel is a built-in debug panel in Flask-DebugToolbar that captures and displays log messages generated during a request. It tracks logs on a per-thread basis using a ThreadTrackingHandler.

    When you view the 'Logging' panel in the toolbar, it displays a list of log records including:

    • message: The formatted log message.
    • time: The timestamp of the log.
    • level: The logging level (e.g., INFO, DEBUG, ERROR).
    • file: The filename (formatted).
    • file_long: The full absolute path to the file.
    • line: The line number where the log was emitted.

    Note that accessing the panel's content via get_and_delete() clears the captured records for the current thread to ensure you only see logs relevant to the current view.

    # No direct code usage required; the panel is automatically available 
    # if Flask-DebugToolbar is configured in your Flask app.
  9. Configure Flask-DebugToolbar options

    main

    You can customize the behavior of the toolbar by setting specific configuration keys in your Flask app.config object. Common options include enabling/disabling specific features like the profiler or template editor, and whitelisting hosts.

    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False