Debugging Django

Simon Willison
Simon WillisonCEO and Co-Founder at Lanyrd
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”
Debugging Django
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/
1 of 19

Recommended

Pluginが広げるRailsの魅力 by
Pluginが広げるRailsの魅力Pluginが広げるRailsの魅力
Pluginが広げるRailsの魅力Yoji Shidara
2.1K views78 slides
Daily Deals from Buy.com by
Daily Deals from Buy.comDaily Deals from Buy.com
Daily Deals from Buy.comdrocallaghan
21 views2 slides
IOS 11 setup with appium latest by
IOS 11 setup with appium  latestIOS 11 setup with appium  latest
IOS 11 setup with appium latestHarikrishna Recharla
406 views6 slides
Tour of Ecto March 2017 Dave Lucia by
Tour of Ecto March 2017 Dave LuciaTour of Ecto March 2017 Dave Lucia
Tour of Ecto March 2017 Dave LuciaDavid Lucia
105 views36 slides
Cucumber testing by
Cucumber testingCucumber testing
Cucumber testingYogesh Waghmare
2.4K views6 slides
Look Who's Talking by
Look Who's TalkingLook Who's Talking
Look Who's TalkingPablo Cantero
791 views28 slides

More Related Content

What's hot

Rajashekaran vengalil building cross browser html5 websites by
Rajashekaran vengalil building cross browser html5 websitesRajashekaran vengalil building cross browser html5 websites
Rajashekaran vengalil building cross browser html5 websitessuniltomar04
249 views33 slides
Como construir uma Aplicação que consuma e produza updates no Twitter usando ... by
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
537 views56 slides
So What If I Am A Private Ohmusha Sales Rep by
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
1.2K views68 slides
Building com Phing - 7Masters PHP by
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHPiMasters
2.4K views13 slides
InstantRails how to by
InstantRails how toInstantRails how to
InstantRails how toYuichiro MASUI
1.7K views16 slides
Engines by
EnginesEngines
EnginesFernand Galiana
1.9K views39 slides

What's hot(14)

Rajashekaran vengalil building cross browser html5 websites by suniltomar04
Rajashekaran vengalil building cross browser html5 websitesRajashekaran vengalil building cross browser html5 websites
Rajashekaran vengalil building cross browser html5 websites
suniltomar04249 views
Como construir uma Aplicação que consuma e produza updates no Twitter usando ... by Cirdes Filho
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 Filho537 views
So What If I Am A Private Ohmusha Sales Rep by Shintaro Kakutani
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
Shintaro Kakutani1.2K views
Building com Phing - 7Masters PHP by iMasters
Building com Phing - 7Masters PHPBuilding com Phing - 7Masters PHP
Building com Phing - 7Masters PHP
iMasters2.4K views
Faceted navigation in Plone 5 by Alin Voinea
Faceted navigation in Plone 5Faceted navigation in Plone 5
Faceted navigation in Plone 5
Alin Voinea530 views
Introduction to Chatbot Development for Facebook Messenger using Python by Muhamad Ishlah
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
Muhamad Ishlah178 views
Vermont Code Camp 2014 Simple Rover with RaspberryPi by John Cicilio
Vermont Code Camp 2014   Simple Rover with RaspberryPiVermont Code Camp 2014   Simple Rover with RaspberryPi
Vermont Code Camp 2014 Simple Rover with RaspberryPi
John Cicilio844 views
Puppet Camp Atlanta 2014: Continuous Deployment of Puppet Modules by Puppet
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
Puppet1.6K views

Viewers also liked

Creating a site structure for the future by
Creating a site structure for the futureCreating a site structure for the future
Creating a site structure for the futureGizmo Creative Factory, Inc.
1.2K views31 slides
Atonement Tree - acrylic painting by
Atonement Tree - acrylic paintingAtonement Tree - acrylic painting
Atonement Tree - acrylic paintingTataro
264 views1 slide
Art in name by
Art   in   nameArt   in   name
Art in nameazulviarosa
443 views15 slides
Sponsorship of Outdoor Events by
Sponsorship of Outdoor EventsSponsorship of Outdoor Events
Sponsorship of Outdoor EventsChris Middleton
875 views15 slides
TechCrunch Media Overview 2015 by
TechCrunch Media Overview 2015TechCrunch Media Overview 2015
TechCrunch Media Overview 2015Jeff Taylor
509 views17 slides
Módulo02 litearcia da informação by
Módulo02 litearcia da informaçãoMódulo02 litearcia da informação
Módulo02 litearcia da informaçãoJoão Alves Dos Reis
426 views6 slides

Viewers also liked(20)

Atonement Tree - acrylic painting by Tataro
Atonement Tree - acrylic paintingAtonement Tree - acrylic painting
Atonement Tree - acrylic painting
Tataro264 views
TechCrunch Media Overview 2015 by Jeff Taylor
TechCrunch Media Overview 2015TechCrunch Media Overview 2015
TechCrunch Media Overview 2015
Jeff Taylor509 views
Como tirar sua ideia do papel by idekos
Como tirar sua ideia do papelComo tirar sua ideia do papel
Como tirar sua ideia do papel
idekos1.3K views
User Experience Designer Prasanna Kate by Prasanna kate
User Experience Designer Prasanna Kate User Experience Designer Prasanna Kate
User Experience Designer Prasanna Kate
Prasanna kate1K views
Let's Predict the Future: B1 Predicting Needs and Risks by lisbk
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
lisbk1.3K views
L’os d’isgango i l’os lebombo by paumolist
L’os d’isgango i l’os lebomboL’os d’isgango i l’os lebombo
L’os d’isgango i l’os lebombo
paumolist450 views
Organic Sustainable Foods: Solutions for Health Crisis & Climate Change by Maggie Jacobs
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
Maggie Jacobs907 views
ACS San Diego, March 2012, InChI Symposium by Markus Sitzmann
ACS San Diego, March 2012, InChI SymposiumACS San Diego, March 2012, InChI Symposium
ACS San Diego, March 2012, InChI Symposium
Markus Sitzmann7.7K views
MMT Digital at Kentico Connection London 2013 - Responsive Web Design by MMT Digital
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
MMT Digital727 views
Virgin Holidays and News UK - Unleash your mojo by Newsworks
Virgin Holidays and News UK - Unleash your mojoVirgin Holidays and News UK - Unleash your mojo
Virgin Holidays and News UK - Unleash your mojo
Newsworks1.2K views
Anatomy of an Intranet (Triangle SharePoint User Group) October 2016 by Michael Greene
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
Michael Greene5.1K views
Heroes Press - La rassegna stampa di Heroes meet in Maratea by Scai Comunicazione
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
Scai Comunicazione1.6K views

Similar to Debugging Django

PhpBB meets Symfony2 by
PhpBB meets Symfony2PhpBB meets Symfony2
PhpBB meets Symfony2Fabien Potencier
7.7K views77 slides
Magento Debugging by
Magento DebuggingMagento Debugging
Magento DebuggingYireo
850 views11 slides
The Dojo Build System by
The Dojo Build SystemThe Dojo Build System
The Dojo Build Systemklipstein
1.7K views19 slides
Troubleshooting Plone by
Troubleshooting PloneTroubleshooting Plone
Troubleshooting PloneRicado Alves
2.2K views36 slides
Future of Web Apps: Google Gears by
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
7.9K views41 slides
Metrics-Driven Engineering by
Metrics-Driven EngineeringMetrics-Driven Engineering
Metrics-Driven EngineeringMike Brittain
9K views106 slides

Similar to Debugging Django(20)

Magento Debugging by Yireo
Magento DebuggingMagento Debugging
Magento Debugging
Yireo850 views
The Dojo Build System by klipstein
The Dojo Build SystemThe Dojo Build System
The Dojo Build System
klipstein1.7K views
Troubleshooting Plone by Ricado Alves
Troubleshooting PloneTroubleshooting Plone
Troubleshooting Plone
Ricado Alves2.2K views
Future of Web Apps: Google Gears by dion
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
dion7.9K views
Db2 For I Parallel Data Load by Thomas Wolfe
Db2 For I Parallel Data LoadDb2 For I Parallel Data Load
Db2 For I Parallel Data Load
Thomas Wolfe1.2K views
Debugging & profiling node.js by tomasperezv
Debugging & profiling node.jsDebugging & profiling node.js
Debugging & profiling node.js
tomasperezv718 views
Re-Design with Elixir/OTP by Mustafa TURAN
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
Mustafa TURAN460 views
Google App Engine in 40 minutes (the absolute essentials) by Python Ireland
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 Ireland567 views
Firefox Syncサーバーを建ててみた by Hiromu Yakura
Firefox Syncサーバーを建ててみたFirefox Syncサーバーを建ててみた
Firefox Syncサーバーを建ててみた
Hiromu Yakura8.5K views
Web development automatisation for fun and profit (Artem Daniliants) by LumoSpark
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)
LumoSpark350 views
Djangoアプリのデプロイに関するプラクティス / Deploy django application by Masashi Shibata
Djangoアプリのデプロイに関するプラクティス / Deploy django applicationDjangoアプリのデプロイに関するプラクティス / Deploy django application
Djangoアプリのデプロイに関するプラクティス / Deploy django application
Masashi Shibata12.7K views
How to create a magento controller in magento extension by Hendy Irawan
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
Hendy Irawan14.9K views
Using Geeklog as a Web Application Framework by Dirk Haun
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
Dirk Haun894 views

More from Simon Willison

How Lanyrd does Geo by
How Lanyrd does GeoHow Lanyrd does Geo
How Lanyrd does GeoSimon Willison
5.7K views25 slides
Cheap tricks for startups by
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startupsSimon Willison
8.5K views26 slides
The Django Web Framework (EuroPython 2006) by
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)Simon Willison
2.9K views56 slides
Building Lanyrd by
Building LanyrdBuilding Lanyrd
Building LanyrdSimon Willison
5.4K views65 slides
How we bootstrapped Lanyrd using Twitter's social graph by
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
2.2K views23 slides
Web Services for Fun and Profit by
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and ProfitSimon Willison
2.6K views95 slides

More from Simon Willison(20)

Cheap tricks for startups by Simon Willison
Cheap tricks for startupsCheap tricks for startups
Cheap tricks for startups
Simon Willison8.5K views
The Django Web Framework (EuroPython 2006) by Simon Willison
The Django Web Framework (EuroPython 2006)The Django Web Framework (EuroPython 2006)
The Django Web Framework (EuroPython 2006)
Simon Willison2.9K views
How we bootstrapped Lanyrd using Twitter's social graph by Simon Willison
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
Simon Willison2.2K views
Web Services for Fun and Profit by Simon Willison
Web Services for Fun and ProfitWeb Services for Fun and Profit
Web Services for Fun and Profit
Simon Willison2.6K views
Tricks & challenges developing a large Django application by Simon Willison
Tricks & challenges developing a large Django applicationTricks & challenges developing a large Django application
Tricks & challenges developing a large Django application
Simon Willison13.9K views
Advanced Aspects of the Django Ecosystem: Haystack, Celery & Fabric by Simon Willison
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
Simon Willison26.2K views
Building Things Fast - and getting approval by Simon Willison
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
Simon Willison1.7K views
Rediscovering JavaScript: The Language Behind The Libraries by Simon Willison
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison20.1K views
Building crowdsourcing applications by Simon Willison
Building crowdsourcing applicationsBuilding crowdsourcing applications
Building crowdsourcing applications
Simon Willison10.1K views
Evented I/O based web servers, explained using bunnies by Simon Willison
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
Simon Willison11.7K views
Cowboy development with Django by Simon Willison
Cowboy development with DjangoCowboy development with Django
Cowboy development with Django
Simon Willison16.9K views
Crowdsourcing with Django by Simon Willison
Crowdsourcing with DjangoCrowdsourcing with Django
Crowdsourcing with Django
Simon Willison12.4K views
Class-based views with Django by Simon Willison
Class-based views with DjangoClass-based views with Django
Class-based views with Django
Simon Willison2.7K views
Web App Security Horror Stories by Simon Willison
Web App Security Horror StoriesWeb App Security Horror Stories
Web App Security Horror Stories
Simon Willison13.1K views
Web Security Horror Stories by Simon Willison
Web Security Horror StoriesWeb Security Horror Stories
Web Security Horror Stories
Simon Willison32.1K views

Recently uploaded

Special_edition_innovator_2023.pdf by
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdfWillDavies22
16 views6 slides
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... by
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...Vadym Kazulkin
75 views64 slides
The details of description: Techniques, tips, and tangents on alternative tex... by
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...BookNet Canada
121 views24 slides
handbook for web 3 adoption.pdf by
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdfLiveplex
19 views16 slides
20231123_Camunda Meetup Vienna.pdf by
20231123_Camunda Meetup Vienna.pdf20231123_Camunda Meetup Vienna.pdf
20231123_Camunda Meetup Vienna.pdfPhactum Softwareentwicklung GmbH
28 views73 slides
STPI OctaNE CoE Brochure.pdf by
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdfmadhurjyapb
12 views1 slide

Recently uploaded(20)

Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2216 views
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... by Vadym Kazulkin
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
Vadym Kazulkin75 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada121 views
handbook for web 3 adoption.pdf by Liveplex
handbook for web 3 adoption.pdfhandbook for web 3 adoption.pdf
handbook for web 3 adoption.pdf
Liveplex19 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb12 views
The Importance of Cybersecurity for Digital Transformation by NUS-ISS
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital Transformation
NUS-ISS27 views
Transcript: The Details of Description Techniques tips and tangents on altern... by BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada130 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab15 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi120 views
Future of Learning - Yap Aye Wee.pdf by NUS-ISS
Future of Learning - Yap Aye Wee.pdfFuture of Learning - Yap Aye Wee.pdf
Future of Learning - Yap Aye Wee.pdf
NUS-ISS41 views
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV by Splunk
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
Splunk88 views
Attacking IoT Devices from a Web Perspective - Linux Day by Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri15 views
Five Things You SHOULD Know About Postman by Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman27 views
Black and White Modern Science Presentation.pptx by maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
maryamkhalid291614 views
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... by NUS-ISS
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
NUS-ISS34 views
Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma17 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10209 views

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”
  • 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/