When you are developing web applications you will sooner or later run need to optimize the application performance. I am often developing using Django or Flask. There are good debug plugins for both frameworks. In this article we will look closer at the Django Debug Toolbar. The toolbar has been ported to Flask as well.
Installing the debug toolbar
First off you need to install the toolbar:
pip install django-debug-toolbar
If your’e not using
pip you could always fetch the code from the project GitHub page
We start with adding a new middleware class in
settings.py. This is a standard
MIDDLEWARE_CLASSES from Django. The observant reader might notice that we have added a new class,
MIDDLEWARE_CLASSES = ( 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
If you haven’t already, you must make sure that your internal IP is added to the
INTERNAL_IPS = ('127.0.0.1',)
You might not have
INTERNAL_IPS defined per default, then just add it.
Finally, you must add
debug_toolbar to you
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'debug_toolbar', )
Debugging with the debug toolbar
You will now have a toolbar on the right side of your web page. Of course, you should configure it to be invisible when you are in production mode. The toolbar will look like this:
There are a bunch of interesting features here, but the one I have found most useful is the SQL query analyzer. Especially in cases where you have many calls or fetch objects via foreign keys from your model.