Django - Know Your Namespace: Middleware

2,359 views

Published on

Presentation for the inaugural django-nyc meetup. We discussed django's middleware namespace as well as the open source django-db-log project.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,359
On SlideShare
0
From Embeds
0
Number of Embeds
28
Actions
Shares
0
Downloads
67
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Django - Know Your Namespace: Middleware

  1. 1. Know your namespace A peek inside a django namespace. (and an open source project implementation: django-db-log)
  2. 2. django.middleware
  3. 3. Pluggable
  4. 4. why do i care? simple dummy...
  5. 5. available middleware provides: • session handling • internationalization • caching • db transactions • authentication • gzip compression • flat pages • etc.
  6. 6. ...umm, yea i could use those.
  7. 7. activating middleware MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', )
  8. 8. need a custom solution?
  9. 9. easy as pie
  10. 10. Simple Guidelines • don’t have to subclass anything • live anywhere on the python path (reusable!) • must define one or more of these 4 methods...
  11. 11. feeling the flow, being the ball process process process call view request view response exception? process exception
  12. 12. Real World Example
  13. 13. from models import Error, ErrorBatch import traceback import socket import warnings Look mom, no hands! import 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))
  14. 14. Discussion • http://code.google.com/p/django-db-log/ • http://www.davidcramer.net/ • http://www.djangoproject.com/documentation/middleware/

×