# insert templess root dir into path import sys, os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) import templess class cgitemplate(object): """ simple cgi engine for serving templess templates """ def __init__(self, template, content_type='text/html; charset=UTF-8', error_template='templates/cgierror.html', headers={}): self.template = template self.content_type = content_type self.error_template = error_template self.headers = headers def render(self, context): """ render and output the document this also prints the Content-Type header, if you want it to print other headers use the headers arg of the constructor """ if not context.has_key('footer'): context['footer'] = templess.__footer__ try: fp = open(self.template) try: t = templess.template(fp) ret = t.render_to_string(context, html=True) finally: fp.close() assert type(ret) == str self.print_output(self.content_type, ret) except: import sys exc, e, tb = sys.exc_info() ret = self.handle_exception(exc, e, tb) def handle_exception(self, exc, e, tb): """ internal method that generates and prints an exception page """ from traceback import format_tb tblist = format_tb(tb) fp = open(self.error_template) try: t = templess.template(fp) context = { 'exception': str(exc), 'message': str(e), 'traceback': '\n'.join(tblist), 'tblist': [{'line': str(l)} for l in tblist], 'footer': __footer__, } ret = t.render_to_string(context, html=True) finally: fp.close() self.print_output('text/html; charset=UTF-8', ret) def print_output(self, content_type, body): """ actually print the output """ print 'Content-Type: %s' % content_type for kv in self.headers.items(): print '%s: %s' % kv print print body