Login

Soft Timeout Middleware

Author:
adamlofts
Posted:
June 19, 2009
Language:
Python
Version:
1.0
Tags:
middleware timeout
Score:
1 (after 1 ratings)

This middleware implements a "soft timeout". This means the admin is sent an email whenever a page time exceeds a certian value. It is intended to run on production servers to inform the admin of any pages which are performing slowly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from time import time

from django.contrib.sites.models import Site
from django.core.mail import mail_admins

class StatsMiddleware(object):

    """ If the soft limit is exceeded then StatsMiddleware will send an email to the admin with details of the request """
    SOFT_LIMIT_SECONDS = 5.0
    
    SOFT_LIMIT_SUBJECT = "Soft Timeout: %s"
    SOFT_LIMIT_MESSAGE = \
"""The soft timeout (%f secs) has been exceeded.
Time: %f
URL: %s
"""

    # fixme: Implement hard limit?
    #        Strategy would probably be to spawn a monitor thread which checks that the request has finished in time
    #        which raises an exception along the lines of: http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python
    #        Maybe better to leave hard limit of mod_wsgi ?
        
    def process_view(self, request, view_func, view_args, view_kwargs):

        start = time()
        response = view_func(request, *view_args, **view_kwargs)
        elapsed = time() - start
        
        if elapsed > StatsMiddleware.SOFT_LIMIT_SECONDS:
            site = Site.objects.get_current()
            url = 'http://%s%s' % (site.domain, request.path)
            subject = StatsMiddleware.SOFT_LIMIT_SUBJECT % url
            message = StatsMiddleware.SOFT_LIMIT_MESSAGE % (StatsMiddleware.SOFT_LIMIT_SECONDS, elapsed, url)
            mail_admins(subject, message, True)
        return response

More like this

  1. Restrict staff access to admin pages by slink 4 years, 5 months ago
  2. Template tag for importing content from external url by dchandek 6 years, 11 months ago
  3. Middleware to prevent access to the admin when user ip not in INTERNAL_IPS by jezdez 4 years, 8 months ago
  4. Technical 500 by group membership by jdunck 5 years, 6 months ago
  5. Current Page Middleware by brutasse 4 years, 9 months ago

Comments

Please login first before commenting.