django - know your namespace: middleware

14
Know your namespace A peek inside a django namespace. (and an open source project implementation: django-db-log)

Upload: howiworkdaily

Post on 15-Jan-2015

1.957 views

Category:

Technology


1 download

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

Page 1: Django - Know Your Namespace: Middleware

Know your namespace A peek inside a django namespace.

(and an open source project implementation: django-db-log)

Page 2: Django - Know Your Namespace: Middleware

django.middleware

Page 3: Django - Know Your Namespace: Middleware

Pluggable

Page 4: Django - Know Your Namespace: Middleware

why do i care?

simple dummy...

Page 5: Django - Know Your Namespace: Middleware

• session handling

• caching

• authentication

• flat pages

• internationalization

• db transactions

• gzip compression

• etc.

available middleware provides:

Page 6: Django - Know Your Namespace: Middleware

...umm, yea i could use those.

Page 7: Django - Know Your Namespace: Middleware

activating middleware

MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware',)

Page 8: Django - Know Your Namespace: Middleware

need a custom solution?

Page 9: Django - Know Your Namespace: Middleware

easy as pie

Page 10: Django - Know Your Namespace: Middleware

Simple Guidelines• don’t have to subclass anything

• live anywhere on the python path (reusable!)

• must define one or more of these 4 methods...

Page 11: Django - Know Your Namespace: Middleware

feeling the flow, being the ball

processrequest

processview

processresponse

processexception

call view

exception?

Page 12: Django - Know Your Namespace: Middleware

Real World Example

Page 13: Django - Know Your Namespace: Middleware

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!