Created
November 26, 2013 22:45
-
-
Save rjzak/7667679 to your computer and use it in GitHub Desktop.
Use this middleware for Django to append the load time to each page. Add it to the middleware config in your settings.py file. If you wish to disable it for a given view, use the @PageLoadExempt decorator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.utils.decorators import decorator_from_middleware, available_attrs | |
from functools import wraps | |
import time | |
class PageLoadTimerMiddleware: | |
def __init__(self): | |
self.initTime = time.clock() | |
self.disabled = False | |
def process_request(self, request): | |
self.requestTime = time.clock() | |
def process_response(self, request, response): | |
if self.disabled: | |
return response | |
responseTime = time.clock() | |
timeDiff = responseTime - self.initTime | |
response.content += "<br/>Elapsed time: %1.2f seconds." % (timeDiff) | |
return response | |
def process_view(self, request, view_func, view_args, view_kwargs): | |
if getattr(view_func, 'pageLoadExempt', False): | |
self.disabled = True | |
return None | |
def PageLoadExempt(view_func): | |
def wrapped_view(*args, **kwargs): | |
return view_func(*args, **kwargs) | |
wrapped_view.pageLoadExempt = True | |
return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment