summaryrefslogtreecommitdiff
path: root/tmpl.py
diff options
context:
space:
mode:
Diffstat (limited to 'tmpl.py')
-rw-r--r--tmpl.py50
1 files changed, 50 insertions, 0 deletions
diff --git a/tmpl.py b/tmpl.py
new file mode 100644
index 0000000..6551728
--- /dev/null
+++ b/tmpl.py
@@ -0,0 +1,50 @@
+import os, traceback
+
+import cherrypy
+from genshi.core import Stream
+from genshi.output import encode, get_serializer
+from genshi.template import Context, TemplateLoader
+
+loader = TemplateLoader(
+ os.path.join(os.path.dirname(__file__), 'templates'),
+ auto_reload=True
+)
+
+def render(*args, **kwargs):
+ if args:
+ assert len(args) == 1, 'Expected exactly one argument, but got %r' % (args,)
+ template = loader.load(args[0])
+ else:
+ template = cherrypy.thread_data.template
+ #ctxt = Context(url = cherrypy.url)
+ ctxt = Context(url = myurl)
+ ctxt.push(kwargs)
+ return template.generate(ctxt)
+
+def exc(exc):
+ return render('error.html', details = traceback.format_exc())
+
+def expose(filename, method='html', encoding='utf-8', **options):
+ def decorate(func):
+ @cherrypy.expose
+ def wrapper(*args, **kwargs):
+ cherrypy.thread_data.template = loader.load(filename)
+ cherrypy.thread_data.func = func
+ opt = options.copy()
+ if method == 'html':
+ opt.setdefault('doctype', 'html')
+ serializer = get_serializer(method, **opt)
+ try:
+ stream = func(*args, **kwargs)
+ except Exception, e:
+ stream = exc(e)
+ if not isinstance(stream, Stream):
+ return stream
+ return encode(serializer(stream), method = serializer, encoding = encoding)
+ return wrapper
+ return decorate
+
+def myurl(url):
+ return '/subdap/' + url
+
+