SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
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/

Más contenido relacionado

La actualidad más candente

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
suniltomar04
 
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 Rep
Shintaro Kakutani
 
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
Puppet
 

La actualidad más candente (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
 

Destacado

Módulo02 litearcia da informação
Módulo02 litearcia da informaçãoMódulo02 litearcia da informação
Módulo02 litearcia da informação
Joã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 papel
idekos
 
User Experience Designer Prasanna Kate
User Experience Designer Prasanna Kate User Experience Designer Prasanna Kate
User Experience Designer Prasanna Kate
Prasanna kate
 
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
paumolist
 
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
Markus Sitzmann
 

Destacado (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 a Debugging Django

Troubleshooting Plone
Troubleshooting PloneTroubleshooting Plone
Troubleshooting Plone
Ricado Alves
 
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 application
Masashi 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 extension
Hendy Irawan
 

Similar a 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
 

Más de Simon Willison

Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
Simon 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 Libraries
Simon Willison
 

Más de 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
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

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/