| 1 | = Page Stats Middleware = |
| 2 | |
| 3 | Display performance metrics measured during the generation of a page. Allows you to display total time, python time, database time, and number of queries for the rendered page. |
| 4 | |
| 5 | == The Python Code == |
| 6 | |
| 7 | {{{ |
| 8 | #!python |
| 9 | import re |
| 10 | from operator import add |
| 11 | from time import time |
| 12 | from django.db import connection |
| 13 | |
| 14 | class StatsMiddleware(object): |
| 15 | |
| 16 | def process_view(self, request, view_func, view_args, view_kwargs): |
| 17 | |
| 18 | # turn on debugging in db backend to capture time |
| 19 | from django.conf import settings |
| 20 | debug = settings.DEBUG |
| 21 | settings.DEBUG = True |
| 22 | |
| 23 | # get number of db queries before we do anything |
| 24 | n = len(connection.queries) |
| 25 | |
| 26 | # time the view |
| 27 | start = time() |
| 28 | response = view_func(request, *view_args, **view_kwargs) |
| 29 | totTime = time() - start |
| 30 | |
| 31 | # compute the db time for the queries just run |
| 32 | queries = len(connection.queries) - n |
| 33 | if queries: |
| 34 | dbTime = reduce(add, [float(q['time']) |
| 35 | for q in connection.queries[n:]]) |
| 36 | else: |
| 37 | dbTime = 0.0 |
| 38 | |
| 39 | # and backout python time |
| 40 | pyTime = totTime - dbTime |
| 41 | |
| 42 | # restore debugging setting |
| 43 | settings.DEBUG = debug |
| 44 | |
| 45 | stats = { |
| 46 | 'totTime': totTime, |
| 47 | 'pyTime': pyTime, |
| 48 | 'dbTime': dbTime, |
| 49 | 'queries': queries, |
| 50 | } |
| 51 | |
| 52 | # replace the comment if found |
| 53 | if response and response.content: |
| 54 | s = response.content |
| 55 | regexp = re.compile(r'(?P<cmt><!--\s*STATS:(?P<fmt>.*?)-->)') |
| 56 | match = regexp.search(s) |
| 57 | if match: |
| 58 | s = s[:match.start('cmt')] + \ |
| 59 | match.group('fmt') % stats + \ |
| 60 | s[match.end('cmt'):] |
| 61 | response.content = s |
| 62 | |
| 63 | return response |
| 64 | }}} |
| 65 | |
| 66 | |
| 67 | == The HTML == |
| 68 | |
| 69 | Put a comment in your template in this format: |
| 70 | {{{ |
| 71 | <!-- STATS: format_string --> |
| 72 | }}} |
| 73 | |
| 74 | Example: |
| 75 | {{{ |
| 76 | <!-- STATS: Total: %(totTime).2f Python: %(pyTime).2f DB: %(dbTime).2f Queries: %(queries)d --> |
| 77 | }}} |