contenttransformer
view contenttransformer/transformers.py @ 20:32a05d7bb214
remove hack around downstream snafu (martINI, ConfigParser)
| author | Jeff Hammel <jhammel@mozilla.com> |
|---|---|
| date | Thu Nov 25 11:55:55 2010 -0800 (18 months ago) |
| parents | 6cbe4172b54b |
| children |
line source
1 import docutils.core
2 import subprocess
3 from utils import import_path
4 from webob import Request, Response
6 import genshi
7 from genshi.template import MarkupTemplate
9 class Transformer(object):
10 """abstract base class for transformer objects"""
11 def __init__(self, content, content_type):
12 self.content = content
13 self.content_type = content_type
15 def transform(self, request):
16 """returns a tuple of (body, content-type)"""
17 raise NotImplementedError
19 def __call__(self, environ, start_response):
20 request = Request(environ)
21 response = self.get_response(request)
22 return response(environ, start_response)
24 def get_response(self, request):
25 if request.GET.get('format') == 'raw':
26 return Response(content_type=self.content_type, body=self.content)
27 content_type, body = self.transform(request)
28 return Response(content_type=content_type, body=body)
30 class ContentTypeChanger(Transformer):
31 def __init__(self, content, from_type, to_type):
32 self.to_type = to_type
33 Transformer.__init__(self, content, from_type)
35 def transform(self, request):
36 return (self.to_type, self.content)
38 class Graphviz(Transformer):
39 content_types = { 'png': 'image/png',
40 'svg': 'image/svg+xml' }
42 def __init__(self, content, content_type, format='png'):
43 self.format=format
44 Transformer.__init__(self, content, content_type)
46 def transform(self, request):
47 """create a Graphviz object"""
48 _format = request.GET.get('format', self.format)
49 assert _format in self.content_types, 'Unknown format: ' + _format
50 process = subprocess.Popen(['dot', '-T' + _format],
51 stdin=subprocess.PIPE,
52 stdout=subprocess.PIPE)
53 image, _ = process.communicate(self.content)
54 return (self.content_types[_format], image)
56 class RestructuredText(Transformer):
57 settings = { 'report_level': 5 }
59 def transform(self, request):
60 """template: genshi(?) template to use (???)"""
61 html = docutils.core.publish_string(self.content,
62 writer_name='html',
63 settings_overrides=self.settings)
64 return ('text/html', html)
67 class GenshiTransformer(Transformer):
69 def __init__(self, content, content_type, modules=()):
70 """
71 - modules : strings of modules
72 """
73 self.variables = {}
74 for path in modules:
75 module = import_path(path)
76 name = path.rsplit('.')[-1]
77 self.variables[name] = module
78 Transformer.__init__(self, content, content_type)
80 def transform(self, request):
81 variables = dict(request=request)
82 template = MarkupTemplate(self.content)
83 stream = template.generate(**variables)
84 return ('text/html', stream.render('html', doctype='html'))
