[Twisted-web] /freeform_post!!random causes exceptions

Andrea Arcangeli andrea at cpushare.com
Mon Jan 10 09:51:30 MST 2005


On Mon, Jan 10, 2005 at 09:23:25PM +1100, Christopher Armstrong wrote:
> Definitely interested in that traceback emailer. That would rock for
> deployed sites.

I did it for my site, indeed ;).

Here the relevant part:

DEBUG_IP = '127.0.0.1'
[..]
from cpushare.web.web import XMLDIR, DEBUG_IP

class basepage_class(rend.Page):
[..]
	def locateChild(self, ctx, segments):
		ctx.remember(page_404(), inevow.ICanHandleNotFound)

		req = inevow.IRequest(ctx)
		if req.getClientIP() != DEBUG_IP:
			#ctx.remember(appserver.UninformativeExceptionHandler(), inevow.ICanHandleException)
			ctx.remember(MyExceptionHandler(), inevow.ICanHandleException)

		return super(basepage_class, self).locateChild(ctx, segments)
[..]

# error pages below

class error_page_class(basepage_class):
	def render_last_link(self, ctx, data):
		referer = inevow.IRequest(ctx).getHeader('referer')
		if referer:
			return ctx.tag[tags.a(href=referer)['previous page']]
		else:
			return ctx.tag[tags.a(href=url.root)['home page']]

class internal_server_error(error_page_class):
	docFactory = loaders.xmlfile('internal_server_error.xml', XMLDIR)

class page_404(error_page_class):
	__implements__ = inevow.ICanHandleNotFound, error_page_class.__implements__
	docFactory = loaders.xmlfile('404.xml', XMLDIR)

	def renderHTTP_notFound(self, ctx):
		inevow.IRequest(ctx).setResponseCode(404)
		return self.renderHTTP(ctx)

INTERNAL_SERVER_ERROR = 'internal_server_error'

class MyExceptionHandler(object):
	__implements__ = inevow.ICanHandleException
	def renderHTTP_exception(self, ctx, reason):
		log.err(reason)
		mail.send_exception(reason)

		request = inevow.IRequest(ctx)
		from twisted.web import util, server
		util.redirectTo(flat.flatten(url.URL.fromContext(ctx).click('/' + INTERNAL_SERVER_ERROR), ctx), request)
		server.Request.finish(request)

	def renderInlineException(self, context, reason):
		log.err(reason)
		mail.send_exception(reason)

		return """<div style="border: 1px dashed red; color: red; clear: both">[[ERROR]]</div>"""
[..]

here the mail.py module:

from twisted.mail.smtp import sendmail
from email.MIMEText import MIMEText

SMTP_SERVER = 'localhost'

def send_exception(reason):
	FROM = 'postmaster at cpushare.com'
	SUBJECT = 'Cpushare Exception'
	TO = 'postmaster at cpushare.com'
	MSG = reason.getTraceback()

	msg = MIMEText(MSG)
	msg['Subject'] = SUBJECT
	msg['From'] = FROM
	msg['To'] = TO
	return sendmail(SMTP_SERVER, FROM, TO, msg)


Then you've to implement the '/' + INTERNAL_SERVER_ERROR page separately
from this.

Sorry for the kernel-like coding style (8 tabs and underscores instead
of uppercase capital letters), but I tend to write it faster that way
and it's more readable to me. It's very easy to convert to a more
pythonic coding style if needed ;).

Hope this helps.



More information about the Twisted-web mailing list