SlideShare a Scribd company logo
1 of 19
Download to read offline
Debugging Django



Simon Willison
DJUGL, 19th May 2008
This talk is not about

 Test Driven
Development

               http://www.flickr.com/photos/alikaragoz/209296304/
This talk is about

 Bug Driven
Development
http://www.shipmentoffail.com/fails/2008/04/horse-vs-car-fail/
Make the most of the error page

Print statements and logging

Using the debugger

Catching errors in production

Abusing the Test Client
The Django error page

  It’s not just for errors!
  Trigger it explicitly with “assert False”
  Show a value with “assert False, variable”
Logging to your console
def index(req):
    print quot;Hello there!quot;


[19/May/2008 18:14:39] quot;GET /static/css/img/
djangosite80x15.gif HTTP/1.1quot; 304 0
[19/May/2008 18:14:39] quot;GET /static/css/img/purple-
gradient.png HTTP/1.1quot; 304 0
Hello there!
[19/May/2008 18:14:47] quot;GET / HTTP/1.1quot; 200 12570
Logging to your console
# in settings.py
import logging
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(message)s',
)

# Anywhere else
import logging
logging.debug(quot;A log messagequot;)
Logging to a file
# in settings.py
import logging
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(message)s',
    filename = '/tmp/dango.log',
    filemode = 'w'
)

# Anywhere else
import logging
logging.debug(quot;A log messagequot;)

$ tail -f /tmp/django.log
Logging the calling context

import logging, traceback, pprint

def my_buggy_function(arg):
    context = pprint.pformat(traceback.extract_stack())
    logging.debug(context)
Using the debugger

import pdb; pdb.set_trace()

$ python -i ./manage.py ...
...
>>> import pdb; pdb.pm()
Errors in production
Two misleadingly-named settings:
# Receive 500 error e-mails if not DEBUG
ADMINS = (
    ('Simon Willison', 'simon@simonwillison.net'),
)

# Receive 404 e-mails if SEND_BROKEN_LINK_EMAILS
MANAGERS = (
    ...
)
IGNORABLE_404_ENDS = ('.php', '.cgi')
Errors over XMPP
db-error-log
Custom error middleware
class DBLogMiddleware(object):
    def process_exception(self, request, exception):
        server_name = socket.gethostname()
        tb_text     = traceback.format_exc()
        class_name = exception.__class__.__name__
        ...

# in settings.py
MIDDLEWARE_CLASSES = (
    ...,
    'djangodblog.DBLogMiddleware',
)
More useful middleware

  ProfilerMiddleware
   See profiler output with url?prof
  DebugFooter
   SQL and templates logged in footer
Abusing the test client

from django.test.utils import setup_test_environment
setup_test_environment()

from django.test.client import Client
c = Client()

r = c.get('/2008/speaking/')
print r
r.template
r.context
Test Driven Development


  www.djangoproject.com/documentation/testing/
  www.slideshare.net/simon/advanced-django/

More Related Content

What's hot

Rajashekaran vengalil building cross browser html5 websites
Rajashekaran vengalil building cross browser html5 websitesRajashekaran vengalil building cross browser html5 websites
Rajashekaran vengalil building cross browser html5 websitessuniltomar04
 
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Cirdes Filho
 
So What If I Am A Private Ohmusha Sales Rep
So What If I Am A Private Ohmusha Sales RepSo What If I Am A Private Ohmusha Sales Rep
So What If I Am A Private Ohmusha Sales RepShintaro Kakutani
 
Building com Phing - 7Masters PHP
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHPiMasters
 
Faceted navigation in Plone 5
Faceted navigation in Plone 5Faceted navigation in Plone 5
Faceted navigation in Plone 5Alin Voinea
 
Introduction to Chatbot Development for Facebook Messenger using Python
Introduction to Chatbot Development for Facebook Messenger using PythonIntroduction to Chatbot Development for Facebook Messenger using Python
Introduction to Chatbot Development for Facebook Messenger using PythonMuhamad Ishlah
 
Vermont Code Camp 2014 Simple Rover with RaspberryPi
Vermont Code Camp 2014   Simple Rover with RaspberryPiVermont Code Camp 2014   Simple Rover with RaspberryPi
Vermont Code Camp 2014 Simple Rover with RaspberryPiJohn Cicilio
 
Puppet Camp Atlanta 2014: Continuous Deployment of Puppet Modules
Puppet Camp Atlanta 2014: Continuous Deployment of Puppet ModulesPuppet Camp Atlanta 2014: Continuous Deployment of Puppet Modules
Puppet Camp Atlanta 2014: Continuous Deployment of Puppet ModulesPuppet
 

What's hot (14)

Rajashekaran vengalil building cross browser html5 websites
Rajashekaran vengalil building cross browser html5 websitesRajashekaran vengalil building cross browser html5 websites
Rajashekaran vengalil building cross browser html5 websites
 
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
Como construir uma Aplicação que consuma e produza updates no Twitter usando ...
 
So What If I Am A Private Ohmusha Sales Rep
So What If I Am A Private Ohmusha Sales RepSo What If I Am A Private Ohmusha Sales Rep
So What If I Am A Private Ohmusha Sales Rep
 
Building com Phing - 7Masters PHP
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHP
 
InstantRails how to
InstantRails how toInstantRails how to
InstantRails how to
 
Engines
EnginesEngines
Engines
 
Faceted navigation in Plone 5
Faceted navigation in Plone 5Faceted navigation in Plone 5
Faceted navigation in Plone 5
 
I motion
I motionI motion
I motion
 
Hyperlink
HyperlinkHyperlink
Hyperlink
 
Introduction to Chatbot Development for Facebook Messenger using Python
Introduction to Chatbot Development for Facebook Messenger using PythonIntroduction to Chatbot Development for Facebook Messenger using Python
Introduction to Chatbot Development for Facebook Messenger using Python
 
Vermont Code Camp 2014 Simple Rover with RaspberryPi
Vermont Code Camp 2014   Simple Rover with RaspberryPiVermont Code Camp 2014   Simple Rover with RaspberryPi
Vermont Code Camp 2014 Simple Rover with RaspberryPi
 
Puppet Camp Atlanta 2014: Continuous Deployment of Puppet Modules
Puppet Camp Atlanta 2014: Continuous Deployment of Puppet ModulesPuppet Camp Atlanta 2014: Continuous Deployment of Puppet Modules
Puppet Camp Atlanta 2014: Continuous Deployment of Puppet Modules
 
Csharp_Contents
Csharp_ContentsCsharp_Contents
Csharp_Contents
 
Rails::Engine
Rails::EngineRails::Engine
Rails::Engine
 

Viewers also liked

Atonement Tree - acrylic painting
Atonement Tree - acrylic paintingAtonement Tree - acrylic painting
Atonement Tree - acrylic paintingTataro
 
Sponsorship of Outdoor Events
Sponsorship of Outdoor EventsSponsorship of Outdoor Events
Sponsorship of Outdoor EventsChris Middleton
 
TechCrunch Media Overview 2015
TechCrunch Media Overview 2015TechCrunch Media Overview 2015
TechCrunch Media Overview 2015Jeff Taylor
 
Módulo02 litearcia da informação
Módulo02 litearcia da informaçãoMódulo02 litearcia da informação
Módulo02 litearcia da informaçãoJoão Alves Dos Reis
 
Como tirar sua ideia do papel
Como tirar sua ideia do papelComo tirar sua ideia do papel
Como tirar sua ideia do papelidekos
 
User Experience Designer Prasanna Kate
User Experience Designer Prasanna Kate User Experience Designer Prasanna Kate
User Experience Designer Prasanna Kate Prasanna kate
 
Let's Predict the Future: B1 Predicting Needs and Risks
Let's Predict the Future: B1 Predicting Needs and RisksLet's Predict the Future: B1 Predicting Needs and Risks
Let's Predict the Future: B1 Predicting Needs and Riskslisbk
 
L’os d’isgango i l’os lebombo
L’os d’isgango i l’os lebomboL’os d’isgango i l’os lebombo
L’os d’isgango i l’os lebombopaumolist
 
Organic Sustainable Foods: Solutions for Health Crisis & Climate Change
Organic Sustainable Foods: Solutions for Health Crisis & Climate ChangeOrganic Sustainable Foods: Solutions for Health Crisis & Climate Change
Organic Sustainable Foods: Solutions for Health Crisis & Climate ChangeMaggie Jacobs
 
ACS San Diego, March 2012, InChI Symposium
ACS San Diego, March 2012, InChI SymposiumACS San Diego, March 2012, InChI Symposium
ACS San Diego, March 2012, InChI SymposiumMarkus Sitzmann
 
MMT Digital at Kentico Connection London 2013 - Responsive Web Design
MMT Digital at Kentico Connection London 2013 - Responsive Web DesignMMT Digital at Kentico Connection London 2013 - Responsive Web Design
MMT Digital at Kentico Connection London 2013 - Responsive Web DesignMMT Digital
 
Virgin Holidays and News UK - Unleash your mojo
Virgin Holidays and News UK - Unleash your mojoVirgin Holidays and News UK - Unleash your mojo
Virgin Holidays and News UK - Unleash your mojoNewsworks
 
Anatomy of an Intranet (Triangle SharePoint User Group) October 2016
Anatomy of an Intranet (Triangle SharePoint User Group) October 2016Anatomy of an Intranet (Triangle SharePoint User Group) October 2016
Anatomy of an Intranet (Triangle SharePoint User Group) October 2016Michael Greene
 
Heroes Press - La rassegna stampa di Heroes meet in Maratea
Heroes Press - La rassegna stampa di Heroes meet in MarateaHeroes Press - La rassegna stampa di Heroes meet in Maratea
Heroes Press - La rassegna stampa di Heroes meet in MarateaScai Comunicazione
 

Viewers also liked (20)

Creating a site structure for the future
Creating a site structure for the futureCreating a site structure for the future
Creating a site structure for the future
 
Atonement Tree - acrylic painting
Atonement Tree - acrylic paintingAtonement Tree - acrylic painting
Atonement Tree - acrylic painting
 
Art in name
Art   in   nameArt   in   name
Art in name
 
Sponsorship of Outdoor Events
Sponsorship of Outdoor EventsSponsorship of Outdoor Events
Sponsorship of Outdoor Events
 
TechCrunch Media Overview 2015
TechCrunch Media Overview 2015TechCrunch Media Overview 2015
TechCrunch Media Overview 2015
 
Módulo02 litearcia da informação
Módulo02 litearcia da informaçãoMódulo02 litearcia da informação
Módulo02 litearcia da informação
 
Como tirar sua ideia do papel
Como tirar sua ideia do papelComo tirar sua ideia do papel
Como tirar sua ideia do papel
 
User Experience Designer Prasanna Kate
User Experience Designer Prasanna Kate User Experience Designer Prasanna Kate
User Experience Designer Prasanna Kate
 
Let's Predict the Future: B1 Predicting Needs and Risks
Let's Predict the Future: B1 Predicting Needs and RisksLet's Predict the Future: B1 Predicting Needs and Risks
Let's Predict the Future: B1 Predicting Needs and Risks
 
L’os d’isgango i l’os lebombo
L’os d’isgango i l’os lebomboL’os d’isgango i l’os lebombo
L’os d’isgango i l’os lebombo
 
Organic Sustainable Foods: Solutions for Health Crisis & Climate Change
Organic Sustainable Foods: Solutions for Health Crisis & Climate ChangeOrganic Sustainable Foods: Solutions for Health Crisis & Climate Change
Organic Sustainable Foods: Solutions for Health Crisis & Climate Change
 
ACS San Diego, March 2012, InChI Symposium
ACS San Diego, March 2012, InChI SymposiumACS San Diego, March 2012, InChI Symposium
ACS San Diego, March 2012, InChI Symposium
 
MMT Digital at Kentico Connection London 2013 - Responsive Web Design
MMT Digital at Kentico Connection London 2013 - Responsive Web DesignMMT Digital at Kentico Connection London 2013 - Responsive Web Design
MMT Digital at Kentico Connection London 2013 - Responsive Web Design
 
ポロロッカ商法
ポロロッカ商法ポロロッカ商法
ポロロッカ商法
 
Cbo, the Budget Process, and the Outlook
Cbo, the Budget Process, and the OutlookCbo, the Budget Process, and the Outlook
Cbo, the Budget Process, and the Outlook
 
Virgin Holidays and News UK - Unleash your mojo
Virgin Holidays and News UK - Unleash your mojoVirgin Holidays and News UK - Unleash your mojo
Virgin Holidays and News UK - Unleash your mojo
 
Anatomy of an Intranet (Triangle SharePoint User Group) October 2016
Anatomy of an Intranet (Triangle SharePoint User Group) October 2016Anatomy of an Intranet (Triangle SharePoint User Group) October 2016
Anatomy of an Intranet (Triangle SharePoint User Group) October 2016
 
Heroes Press - La rassegna stampa di Heroes meet in Maratea
Heroes Press - La rassegna stampa di Heroes meet in MarateaHeroes Press - La rassegna stampa di Heroes meet in Maratea
Heroes Press - La rassegna stampa di Heroes meet in Maratea
 
A Gentle Introduction to the EM Algorithm
A Gentle Introduction to the EM AlgorithmA Gentle Introduction to the EM Algorithm
A Gentle Introduction to the EM Algorithm
 
FOWD November 2007
FOWD November 2007FOWD November 2007
FOWD November 2007
 

Similar to Debugging Django

Magento Debugging
Magento DebuggingMagento Debugging
Magento DebuggingYireo
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build Systemklipstein
 
Troubleshooting Plone
Troubleshooting PloneTroubleshooting Plone
Troubleshooting PloneRicado Alves
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Metrics-Driven Engineering
Metrics-Driven EngineeringMetrics-Driven Engineering
Metrics-Driven EngineeringMike Brittain
 
Db2 For I Parallel Data Load
Db2 For I Parallel Data LoadDb2 For I Parallel Data Load
Db2 For I Parallel Data LoadThomas Wolfe
 
Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.jstomasperezv
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4Javier Eguiluz
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTPMustafa TURAN
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Python Ireland
 
Firefox Syncサーバーを建ててみた
Firefox Syncサーバーを建ててみたFirefox Syncサーバーを建ててみた
Firefox Syncサーバーを建ててみたHiromu Yakura
 
Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)LumoSpark
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationMasashi Shibata
 
How to create a magento controller in magento extension
How to create a magento controller in magento extensionHow to create a magento controller in magento extension
How to create a magento controller in magento extensionHendy Irawan
 
Grow your own tools - VilniusRB
Grow your own tools - VilniusRBGrow your own tools - VilniusRB
Grow your own tools - VilniusRBRemigijus Jodelis
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 

Similar to Debugging Django (20)

PhpBB meets Symfony2
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2
 
Magento Debugging
Magento DebuggingMagento Debugging
Magento Debugging
 
The Dojo Build System
The Dojo Build SystemThe Dojo Build System
The Dojo Build System
 
Troubleshooting Plone
Troubleshooting PloneTroubleshooting Plone
Troubleshooting Plone
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Metrics-Driven Engineering
Metrics-Driven EngineeringMetrics-Driven Engineering
Metrics-Driven Engineering
 
Db2 For I Parallel Data Load
Db2 For I Parallel Data LoadDb2 For I Parallel Data Load
Db2 For I Parallel Data Load
 
Debugging & profiling node.js
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.js
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)Google App Engine in 40 minutes (the absolute essentials)
Google App Engine in 40 minutes (the absolute essentials)
 
Firefox Syncサーバーを建ててみた
Firefox Syncサーバーを建ててみたFirefox Syncサーバーを建ててみた
Firefox Syncサーバーを建ててみた
 
Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)
 
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django application
 
How to create a magento controller in magento extension
How to create a magento controller in magento extensionHow to create a magento controller in magento extension
How to create a magento controller in magento extension
 
前端概述
前端概述前端概述
前端概述
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Grow your own tools - VilniusRB
Grow your own tools - VilniusRBGrow your own tools - VilniusRB
Grow your own tools - VilniusRB
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Profiling em Python
Profiling em PythonProfiling em Python
Profiling em Python
 

More from Simon Willison

Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startupsSimon Willison
 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)Simon Willison
 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphSimon Willison
 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and ProfitSimon Willison
 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationSimon Willison
 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricSimon Willison
 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses TwitterSimon Willison
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approvalSimon Willison
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesSimon Willison
 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applicationsSimon Willison
 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesSimon Willison
 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with DjangoSimon Willison
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with DjangoSimon Willison
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror StoriesSimon Willison
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror StoriesSimon Willison
 

More from Simon Willison (20)

How Lanyrd does Geo
How Lanyrd does GeoHow Lanyrd does Geo
How Lanyrd does Geo
 
Cheap tricks for startups
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startups
 
The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)
 
Building Lanyrd
Building LanyrdBuilding Lanyrd
Building Lanyrd
 
How we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graphHow we bootstrapped Lanyrd using Twitter's social graph
How we bootstrapped Lanyrd using Twitter's social graph
 
Web Services for Fun and Profit
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and Profit
 
Tricks & challenges developing a large Django application
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django application
 
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & FabricAdvanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric
 
How Lanyrd uses Twitter
How Lanyrd uses TwitterHow Lanyrd uses Twitter
How Lanyrd uses Twitter
 
ScaleFail
ScaleFailScaleFail
ScaleFail
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
 
Building crowdsourcing applications
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applications
 
Evented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunniesEvented I/O based web servers, explained using bunnies
Evented I/O based web servers, explained using bunnies
 
Cowboy development with Django
Cowboy development with DjangoCowboy development with Django
Cowboy development with Django
 
Crowdsourcing with Django
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with Django
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Web App Security Horror Stories
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror Stories
 
Web Security Horror Stories
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror Stories
 

Recently uploaded

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Recently uploaded (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

Debugging Django

  • 2. This talk is not about Test Driven Development http://www.flickr.com/photos/alikaragoz/209296304/
  • 3. This talk is about Bug Driven Development
  • 5. Make the most of the error page Print statements and logging Using the debugger Catching errors in production Abusing the Test Client
  • 6. The Django error page It’s not just for errors! Trigger it explicitly with “assert False” Show a value with “assert False, variable”
  • 7.
  • 8. Logging to your console def index(req): print quot;Hello there!quot; [19/May/2008 18:14:39] quot;GET /static/css/img/ djangosite80x15.gif HTTP/1.1quot; 304 0 [19/May/2008 18:14:39] quot;GET /static/css/img/purple- gradient.png HTTP/1.1quot; 304 0 Hello there! [19/May/2008 18:14:47] quot;GET / HTTP/1.1quot; 200 12570
  • 9. Logging to your console # in settings.py import logging logging.basicConfig( level = logging.DEBUG, format = '%(asctime)s %(levelname)s %(message)s', ) # Anywhere else import logging logging.debug(quot;A log messagequot;)
  • 10. Logging to a file # in settings.py import logging logging.basicConfig( level = logging.DEBUG, format = '%(asctime)s %(levelname)s %(message)s', filename = '/tmp/dango.log', filemode = 'w' ) # Anywhere else import logging logging.debug(quot;A log messagequot;) $ tail -f /tmp/django.log
  • 11. Logging the calling context import logging, traceback, pprint def my_buggy_function(arg): context = pprint.pformat(traceback.extract_stack()) logging.debug(context)
  • 12. Using the debugger import pdb; pdb.set_trace() $ python -i ./manage.py ... ... >>> import pdb; pdb.pm()
  • 13. Errors in production Two misleadingly-named settings: # Receive 500 error e-mails if not DEBUG ADMINS = ( ('Simon Willison', 'simon@simonwillison.net'), ) # Receive 404 e-mails if SEND_BROKEN_LINK_EMAILS MANAGERS = ( ... ) IGNORABLE_404_ENDS = ('.php', '.cgi')
  • 16. Custom error middleware class DBLogMiddleware(object): def process_exception(self, request, exception): server_name = socket.gethostname() tb_text = traceback.format_exc() class_name = exception.__class__.__name__ ... # in settings.py MIDDLEWARE_CLASSES = ( ..., 'djangodblog.DBLogMiddleware', )
  • 17. More useful middleware ProfilerMiddleware See profiler output with url?prof DebugFooter SQL and templates logged in footer
  • 18. Abusing the test client from django.test.utils import setup_test_environment setup_test_environment() from django.test.client import Client c = Client() r = c.get('/2008/speaking/') print r r.template r.context
  • 19. Test Driven Development www.djangoproject.com/documentation/testing/ www.slideshare.net/simon/advanced-django/