import logging import xtraceback import pprint import sys from cgi import escape from mandaye.http import HTTPResponse, HTTPHeader from mandaye.config import debug from template import serve_template def _get_html_traceback(tb_str, path, env=None): msg = "

%s

Exception

%s
" % \ (path, escape(tb_str)) if env: env = pprint.pformat(env) msg += '

Environment

%s
' % escape(env) return msg def _302(location, cookies=None): headers = HTTPHeader({'Location': [location], 'Content-Type': ['text/html']}) msg = "Reload the page to get source for: %s" % location return HTTPResponse(302, 'Found', headers, msg, cookies) def _401(msg): title='Unauthorized' logging.warning('401 %s' % msg) headers = HTTPHeader({'Content-Type': ['text/html']}) return HTTPResponse(401, 'Unauthorized', headers, serve_template("response.html", title=title, body=msg)) def _404(path): logging.warning("404 %s not found" % path) title = "Not Found" body = "The requested URL %s was not found on this server." % path headers = HTTPHeader({'Content-Type': ['text/html']}) return HTTPResponse(404, 'Not found', headers, serve_template("response.html", title=title, body=body)) def _500(path, msg, exception=None, env=None): """ Return a 500 error path: the path of this error exception: this exception instance if any """ if exception: tb_str = str(xtraceback.XTraceback(*sys.exc_info(), color=False)) logging.exception("500 %s: %s, %s, env: %r" % (path, msg, tb_str, env)) else: logging.error("500 %s: %s, env: %r" % (path, msg, env)) title = 'Internal Server Error' headers = HTTPHeader({'Content-Type': ['text/html']}) if debug: if exception: msg += _get_html_traceback(tb_str, path, env=env) else: msg=msg else: msg = "The server encountered an internal error or misconfiguration \ and was unable to complete your request. Please contact the server \ administrator and inform them of the time the error occurred." return HTTPResponse(500, 'Internal Server Error', headers, serve_template("response.html", title=title, body=msg)) def _502(path, target_hostname, exception=None): """ Return a 502 error path: the path of this error exception: this exception instance if any """ logging.critical("[502] error while reading %s:\n" % path) title = 'Bad Gateway' headers = HTTPHeader({'Content-Type': ['text/html']}) msg = "The server can't join the target server or misconfiguration \ and was unable to complete your request. Please contact the server \ administrator and inform them of the time the error occurred." if debug and exception: traceback.print_exc() msg = "

Target hostname: %s

" % target_hostname msg += _get_html_traceback(exception, path) return HTTPResponse(502, 'Bad Gateway', headers, serve_template("response.html", title=title, body=msg)) def template_response(templatename, values): headers = HTTPHeader({'Content-Type': ['text/html']}) msg = serve_template(templatename, **values) return HTTPResponse(200, 'OK', headers, msg)