django - know your namespace: middleware
DESCRIPTION
Presentation for the inaugural django-nyc meetup. We discussed django's middleware namespace as well as the open source django-db-log project.TRANSCRIPT
Know your namespace A peek inside a django namespace.
(and an open source project implementation: django-db-log)
django.middleware
Pluggable
why do i care?
simple dummy...
• session handling
• caching
• authentication
• flat pages
• internationalization
• db transactions
• gzip compression
• etc.
available middleware provides:
...umm, yea i could use those.
activating middleware
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware',)
need a custom solution?
easy as pie
Simple Guidelines• don’t have to subclass anything
• live anywhere on the python path (reusable!)
• must define one or more of these 4 methods...
feeling the flow, being the ball
processrequest
processview
processresponse
processexception
call view
exception?
Real World Example
from models import Error, ErrorBatch
import tracebackimport socketimport warningsimport md5
class DBLogMiddleware(object): def process_exception(self, request, exception): server_name = socket.gethostname() tb_text = traceback.format_exc() class_name = exception.__class__.__name__ checksum = md5.new(tb_text).hexdigest()
defaults = dict( class_name = class_name, message = exception.message, url = request.build_absolute_uri(), server_name = server_name, traceback = tb_text, )
try: Error.objects.create(**defaults) batch, created = ErrorBatch.objects.get_or_create( class_name = class_name, server_name = server_name, checksum = checksum, defaults = defaults ) if not created: batch.times_seen += 1 batch.save() except Exception, exc: warnings.warn(unicode(exc))
Look mom, no hands!
Discussion
• http://code.google.com/p/django-db-log/
• http://www.davidcramer.net/• http://www.djangoproject.com/documentation/middleware/