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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.