diff decoupage/web.py @ 49:ac693b8df32c

add idea of formats and json format
author Jeff Hammel <jhammel@mozilla.com>
date Wed, 03 Nov 2010 08:18:50 -0700
parents af73a3fda723
children d327dc7de14f
line wrap: on
line diff
--- a/decoupage/web.py	Wed Nov 03 07:22:39 2010 -0700
+++ b/decoupage/web.py	Wed Nov 03 08:18:50 2010 -0700
@@ -15,8 +15,9 @@
 from genshi.template.base import TemplateSyntaxError
 from martini.config import ConfigMunger
 from paste.fileapp import FileApp
+from pkg_resources import iter_entry_points
+from pkg_resources import load_entry_point
 from pkg_resources import resource_filename
-from pkg_resources import iter_entry_points
 from webob import Request, Response, exc
 
 transformers = [i.lower() for i in transformers()]
@@ -51,6 +52,18 @@
 
         # static file server
         self.fileserver = FileApp # XXX still used?!?
+
+        # pluggable formats
+        self.formats = {}
+        for _format in iter_entry_points('decoupage.formats'):
+            try:
+                function = _format.load()
+            except Exception, e:
+                # record the error, but persist
+                print >> sys.stderr, "Couldn't load format: %s" % _format
+                print >> sys.stderr, e
+                continue
+            self.formats[_format.name] = function
         
         # pluggable index data formatters
         self.formatters = {}
@@ -60,8 +73,10 @@
                 template_dir = resource_filename(formatter.module_name, 'templates')
                 if template_dir not in self.template_directories and os.path.isdir(template_dir):
                     self.template_directories.append(template_dir)
-            except:
-                print "Couldn't load formatter: %s" % formatter
+            except Exception, e:
+                # record the error, but persist
+                print >> sys.stderr, "Couldn't load formatter: %s" % formatter
+                print >> sts.stderr, e
                 continue 
             self.formatters[formatter.name] = _formatter
         
@@ -148,6 +163,16 @@
             formatter = self.formatters[name](conf.get('/%s' % name, ''))
             formatter(request, data)
 
+        # return an alternate format if specified
+        # decoupage.formats should return a 2-tuple:
+        # (content_type, body)
+        if 'format' in request.GET:
+            format_name = request.GET['format']
+            if format_name in self.formats:
+                function = self.formats[format_name]
+                content_type, body = function(data)
+                return Response(content_type=content_type, body=body)
+
         # render the template
         template = conf.get('/template')
         local_index = False