Skip to content

Commit cae902a

Browse files
committed
Add two middleware classes:
- SQLLogMiddleware. This logs any INSERT or UPDATE performed by a request. - SMTPExceptionMiddleware. This renders a "please try again" (template email_failed.html) message when an attempt to send email failed. This uses a bit of a hack, in that the middleware looks explicitly for smtplib.SMTPException, and smtplib can raise other exceptions (particularly socket errors). utils/mail/send_smtp catches all exceptions and reraises non-smtplib exceptions as fake smtplib exceptions, and the middleware undoes the wrapping. - Legacy-Id: 224
1 parent 600002f commit cae902a

3 files changed

Lines changed: 53 additions & 11 deletions

File tree

ietf/middleware.py

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
1-
2-
# From http://www.djangosnippets.org/snippets/172/
3-
# Uses python-utidylib, http://utidylib.berlios.de/,
4-
# which uses HTML Tidy, http://tidy.sourceforge.net/
5-
6-
import tidy
1+
try:
2+
import tidy
3+
tidyavail = True
4+
except ImportError:
5+
tidyavail = False
6+
from django.db import connection
7+
from django.shortcuts import render_to_response
8+
from django.template import RequestContext
9+
from ietf.utils import log
10+
import re
11+
import smtplib
12+
import sys
13+
import traceback
714

815
options = dict(
916
output_xhtml=True,
@@ -16,11 +23,39 @@
1623

1724

1825
class PrettifyMiddleware(object):
19-
"""Prettify middleware"""
26+
"""Prettify middleware
27+
From http://www.djangosnippets.org/snippets/172/
28+
Uses python-utidylib, http://utidylib.berlios.de/,
29+
which uses HTML Tidy, http://tidy.sourceforge.net/
30+
"""
2031

2132
def process_response(self, request, response):
22-
if response.headers['Content-Type'].split(';', 1)[0] in ['text/html']:
33+
if tidyavail and response.headers['Content-Type'].split(';', 1)[0] in ['text/html']:
2334
content = response.content
2435
content = str(tidy.parseString(content, **options))
2536
response.content = content
2637
return response
38+
39+
class SQLLogMiddleware(object):
40+
def process_response(self, request, response):
41+
for q in connection.queries:
42+
if re.match('(update|insert)', q['sql'], re.IGNORECASE):
43+
log(q['sql'])
44+
return response
45+
46+
class SMTPExceptionMiddleware(object):
47+
def process_exception(self, request, exception):
48+
if isinstance(exception, smtplib.SMTPException):
49+
type = sys.exc_info()[0]
50+
value = sys.exc_info()[1]
51+
# See if it's a non-smtplib exception that we faked
52+
if type == smtplib.SMTPException and len(value.args) == 1 and isinstance(value.args[0], dict) and value.args[0].has_key('really'):
53+
orig = value.args[0]
54+
type = orig['really']
55+
tb = traceback.format_tb(orig['tb'])
56+
value = orig['value']
57+
else:
58+
tb = traceback.format_tb(sys.exc_info()[2])
59+
return render_to_response('email_failed.html', {'exception': type, 'args': value, 'traceback': "".join(tb)},
60+
context_instance=RequestContext(request))
61+
return None

ietf/settings.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@
8181
'django.contrib.auth.middleware.AuthenticationMiddleware',
8282
'django.middleware.doc.XViewMiddleware',
8383
# 'ietf.middleware.PrettifyMiddleware',
84+
'ietf.middleware.SQLLogMiddleware',
85+
'ietf.middleware.SMTPExceptionMiddleware',
8486
'django.middleware.transaction.TransactionMiddleware',
8587
)
8688

ietf/utils/mail.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def send_smtp(msg):
2828
add_headers(msg)
2929
(fname, frm) = parseaddr(msg.get('From'))
3030
to = [addr for name, addr in getaddresses(msg.get_all('To') + msg.get_all('Cc', []))]
31+
server = None
3132
try:
3233
server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT)
3334
if settings.DEBUG:
@@ -37,11 +38,15 @@ def send_smtp(msg):
3738
server.sendmail(frm, to, msg.as_string())
3839
# note: should pay attention to the return code, as it may
3940
# indicate that someone didn't get the email.
40-
except smtplib.SMTPException:
41-
server.quit()
41+
except:
42+
if server:
43+
server.quit()
4244
# need to improve log message
4345
log("got exception '%s' (%s) trying to send email from '%s' to %s subject '%s'" % (sys.exc_info()[0], sys.exc_info()[1], frm, to, msg.get('Subject', '[no subject]')))
44-
raise
46+
if isinstance(sys.exc_info()[0], smtplib.SMTPException):
47+
raise
48+
else:
49+
raise smtplib.SMTPException({'really': sys.exc_info()[0], 'value': sys.exc_info()[1], 'tb': sys.exc_info()[2]})
4550
server.quit()
4651
log("sent email from '%s' to %s subject '%s'" % (frm, to, msg.get('Subject', '[no subject]')))
4752

0 commit comments

Comments
 (0)