This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
mandaye/mandaye/response.py

81 lines
2.9 KiB
Python

import logging
import traceback
from cgi import escape
from mako.lookup import TemplateLookup
from mako.template import Template
from mandaye.http import HTTPResponse, HTTPHeader
from mandaye.config import template_directory, debug
mylookup = TemplateLookup(directories=[template_directory])
def serve_template(templatename, **kwargs):
mytemplate = mylookup.get_template(templatename)
return mytemplate.render(**kwargs)
def _get_html_traceback(exception, path):
traceback.print_exc()
tb_str = traceback.format_exc()
msg = "<h2>%s %s</h2><pre>%s</pre>" % \
(path, exception, escape(tb_str))
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'
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):
""" Return a 500 error
path: the path of this error
exception: this exception instance if any """
logging.critical("[500] %s: %s" % (path, msg))
title = 'Internal Server Error'
headers = HTTPHeader({'Content-Type': ['text/html']})
if debug:
if exception:
msg += _get_html_traceback(exception, path)
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:
msg = "<h2>Target hostname: %s</h2>" % target_hostname
msg += _get_html_traceback(exception, path)
return HTTPResponse(502, 'Bad Gateway', headers,
serve_template("response.html", title=title, body=msg))