Using Flask-DebugToolbar with Flask-SQLAlchemy to View PostgreSQL Queries

Flask-DebugToolbar is a handy Flask extension that integrates with Jinja2 templates to display useful debug information for your Python Flask Web Apps. I was particularly interested in its ability to integrate with Flask-SQLAlchemy to display PostgreSQL Queries.

In this Flask tutorial I will walk you through creating a sample Flask Application that connects to a PostgreSQL Database using Flask-SQLAlchemy. It will query a contacts table to retrieve a single contact, and you will see this query displayed in FLASK-DebugToolbar.

Creating the PostgreSQL Database and contacts table is left to the reader. I have a test contacts_dev database I keep around for testing, but it might be easiest for you to just use SQLite or an existing database.

Create Virtual Environment and Pip Install Python Dependencies

Create a new virtual environment and pip install the necessary dependencies. You can install all these Python dependencies using a single pip install. I used multiple commands because it displays better on the website.

$ mkdir flask-sample && cd $_
$ python -m venv env
$ source env/bin/activate
$ (env) pip install Flask
$ (env) pip install Flask-DebugToolbar
$ (env) pip install Flask-SQLAlchemy
$ (env) pip install psycopg2

Create a Flask Web Application

Let’s create one file, app.py, that contains all our code for the Flask Website.

from flask import Flask, render_template
from flask_debugtoolbar import DebugToolbarExtension
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SECRET_KEY'] = 'too-cool-for-school'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/contacts_dev'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
toolbar = DebugToolbarExtension(app)

@app.route('/contacts/<int:id>')
def get_contact(id):
    contact = Contact.query.get(id)
    return render_template('contact.html', contact=contact)

class Contact(db.Model):
    __tablename__ = 'contacts'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, nullable=False)
    phone = db.Column(db.String(64), index=True, nullable=False)

    def __init__(self, name, phone):
        self.name = name
        self.phone = phone

    def __repr__(self):
        return '<Contact {}>'.format(self.name)

Here is a sample Flask Template for contact.html to display a contact. This is really of no interest to us as we just need to render a template so we can view the Flask-DebugToolbar.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ contact.name }}</title>
</head>
<body>
    <h1>{{ contact.name }}</h1>
    <h2>{{ contact.phone }}</h2>
</body>
</html>

Run the Flask Web App

Run the Flask Web App using Flask’s Development Server. Flask has to be running in debug mode in order to see the toolbar.

$ (env) export FLASK_APP=app.py
$ (env) export FLASK_DEBUG=1
$ (env) flask run
 * Serving Flask app "app"
 * Forcing debug mode on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 418-031-610

View the Flask-DebugToolbar

View the Flask-DebugToolbar by browsing to the local URL. You need to pass in a contact id that exists in the contacts table.

http://localhost:5000/contacts/1

The Flask-DebugToolbar will display on the page and you can view the SQLAlchemy Query.

Debugging Flask Web App SQLAlchemy Queries with Flask-DebugToolbar

The toolbar displays a lot more information so poke around to see what is has to offer.

Deactivate Python 3 Virtual Environment

When you are done, quit the Flask Web App and deactivate the Python 3 Virtual Environment.

$ (env) deactivate
$

Contents