Login

Soft Timeout Middleware

Author:
adamlofts
Posted:
June 19, 2009
Language:
Python
Version:
1.0
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.