# Show how to email Django tracebacks of exceptions under web.py # by Ben Hoyt of http://micropledge.com/ -- Nov 2007 # tested under Apache and mod_wsgi # set to True if you want the Django error page to show to the user (debug only!) # set to False if you want the user to see a friendly page and the error to be emailed to NOTIFY_EMAIL DEBUG = False # change these to suit your setup SMTP_SERVER = 'localhost' NOTIFY_EMAIL = 'your@email.com' ERROR_FILE_PREFIX = 'c:/temp/ee_' ERROR_LINK_PREFIX = 'https://localhost/showtrace/' import sha, smtplib, web from email.MIMEText import MIMEText urls = ( '/', 'home', '/crash', 'crash', '/showtrace/([a-f0-9]+)', 'showtrace' ) application = web.wsgifunc(web.webpyfunc(urls, globals())) def email(subject, body, to, from_=None): if not from_: from_ = to msg = MIMEText(body) msg['Subject'] = subject msg['From'] = from_ msg['To'] = to s = smtplib.SMTP(SMTP_SERVER) try: refused = s.sendmail(from_, to, msg.as_string()) except smtplib.SMTPRecipientsRefused, r: refused = r.recipients s.quit() return refused def inform(page): key = sha.new(page).hexdigest()[:20] f = file(ERROR_FILE_PREFIX + key + '.html', 'wb') f.write(page) link = ERROR_LINK_PREFIX + key email('Exception occurred!', link + '\n', NOTIFY_EMAIL) def internalerror(): web.header('Content-Type', 'text/html') web.ctx.status = "500 Internal Server Error" print 'Render a friendly page for the user here' page = web.djangoerror() inform(page) class home: def GET(self): web.header('Content-Type', 'text/html') print 'crash test' class crash: def GET(self): web.header('Content-Type', 'text/plain') print 1/0 # dummy exception class showtrace: def GET(self, key): # You should do a check here to see if the user is an admin user. # You should also check that they're viewing the traceback over HTTPS, # otherwise potentially critical data like DB passwords can be sent in the clear. web.header('Content-Type', 'text/html') try: f = file(ERROR_FILE_PREFIX + key + '.html', 'rb') except IOError: print 'Error file not found' else: print f.read() # show the error if debug, email the error if not if DEBUG: web.webapi.internalerror = web.debugerror else: web.webapi.internalerror = internalerror