import kid import os from config import config, log import mimeparse import md5 extensions = { 'html': ('text/html; charset=utf-8', 'html'), 'xhtml': ('application/xhtml+xml; charset=utf-8', 'xhtml'), 'atom': ('application/atom+xml; charset=utf-8', 'xml') } matching = { 'text/html; charset=utf-8': 'html', 'application/xhtml+xml; charset=utf-8': 'xhtml' } def render(environ, start_response, template_file, vars, headers={}, status="200 Ok", raw_etag=None): file=os.path.join("templates", template_file) if raw_etag: last_modified = str(os.stat(file).st_mtime) hash = md5.new(raw_etag) hash.update(last_modified) etag = '"%s"' % hash.hexdigest() headers['etag'] = etag if etag == environ.get('HTTP_IF_NONE_MATCH', ''): return http304(environ, start_response) (contenttype, serialization) = ('text/html; charset=utf-8', 'html') ext = template_file.rsplit(".") if len(ext) > 1 and (ext[1] in extensions): (contenttype, serialization) = extensions[ext[1]] # Only serve XHTML to those clients that can understand it. if serialization in matching: best = mimeparse.best_match(matching.keys(), environ.get('HTTP_ACCEPT', 'application/xhtml+xml')) (contenttype, serialization) = (best, match[best]) if serialization == 'xhtml' and environ.get('HTTP_USER_AGENT', '').find("MSIE") >= 0: (contenttype, serialization) = extensions['html'] template = kid.Template(file, **vars) body = template.serialize(output=serialization, encoding='utf-8') headers['Content-Type'] = contenttype start_response(status, list(headers.iteritems())) return [body] def render_json(start_response, struct): import simplejson body = simplejson.dumps(struct) start_response("200 OK", [('Content-Type', 'text/plain')]) return [body] def http404(environ, start_response): log.warning("404: %s" % environ.get('PATH_INFO', '')) start_response("404 Not Found", [('Content-Type', "text/html")]) return ["