1 | from django.conf import settings |
---|
2 | from django.db import signals |
---|
3 | from django.dispatch import dispatcher |
---|
4 | from django.template import loader |
---|
5 | |
---|
6 | class SQLTracker(object): |
---|
7 | def __init__(self): |
---|
8 | self.queries = [] |
---|
9 | |
---|
10 | def add(self, unbound, params, bound, runtime): |
---|
11 | self.queries.append({'unbound': unbound, 'params': params, 'bound': bound, 'runtime': runtime}) |
---|
12 | |
---|
13 | |
---|
14 | class SQLTrackerMiddleware(object): |
---|
15 | def __init__(self, *args, **kwargs): |
---|
16 | print 'SQLTrackerMiddleware being inited' |
---|
17 | |
---|
18 | def process_request(self, request): |
---|
19 | # FIXME: I know this is bad, but I'm not sure where else to put it. |
---|
20 | request.sql_tracker = SQLTracker() |
---|
21 | def track_query(sender, *args, **kwargs): |
---|
22 | display_sql = sender.db.ops.last_executed_query(sender, kwargs['sql'], kwargs['params']) |
---|
23 | request.sql_tracker.add(kwargs['sql'], kwargs['params'], display_sql, kwargs['time']) |
---|
24 | # weak=False is necessary for this to bind here. |
---|
25 | dispatcher.connect(track_query, signal=signals.query_execute, weak=False) |
---|
26 | |
---|
27 | def create_debug_sql_output(self, request, response): |
---|
28 | """ Generates SQL output for debugging. |
---|
29 | |
---|
30 | Separate from process_response so that it is easier to override without |
---|
31 | worrying about the details of attaching it to the response. |
---|
32 | |
---|
33 | """ |
---|
34 | return loader.render_to_string('debug_sql.html', {'queries': request.sql_tracker.queries}) |
---|
35 | |
---|
36 | def process_response(self, request, response): |
---|
37 | if settings.DEBUG: |
---|
38 | # Prevent it from being sent with any non-default content-encodings |
---|
39 | # (anything but plaintext). |
---|
40 | if not response.has_header('Content-Encoding'): |
---|
41 | # FIXME: There's still all sorts of reasons this could fail, let it |
---|
42 | # do so gracefully. |
---|
43 | try: |
---|
44 | response.content += self.create_debug_sql_output(request, response) |
---|
45 | except: |
---|
46 | pass |
---|
47 | return response |
---|