Really simple Django view function timer decorator

08 December 2017   2 comments   Python, Django

I use this sometimes to get insight into how long some view functions take. Perhaps you find it useful too:

def view_function_timer(prefix='', writeto=print
):

    def decorator(func):
        @functools.wraps(func)
        def inner(*args, **kwargs):
            try:
                t0 = time.time()
                return func(*args, **kwargs)
            finally:
                t1 = time.time()
                writeto(
                    'View Function',
                    '({})'.format(prefix) if prefix else '',
                    func.__name__,
                    args[1:],
                    'Took',
                    '{:.2f}ms'.format(1000 * (t1 - t0)),
                    args[0].build_absolute_uri(),
                )
        return inner

    return decorator

And to use it:

from wherever import view_function_timer


@view_function_timer()
def homepage(request, thing):
    ...
    return render(request, template, context)

And then it prints something like this:

View Function  homepage ('valueofthing',) Took 23.22ms http://localhost:8000/home/valueofthing

It's useful when you don't want a full-blown solution to measure all view functions with a middleware or something.
It can be useful also to see how a cache decorator might work:

from django.views.decorators.cache import cache_page
from wherever import view_function_timer


@view_function_timer('possibly cached')
@cache_page(60 * 60 * 2)  # two hours cache
@view_function_timer('not cached')
def homepage(request, thing):
    ...
    return render(request, template, context)

That way you can trace that, with tail -f or something, to see how/if the cacheing decorator works.

There are many better solutions that are more robust but might be a bigger investment. For example, I would recommend markus which, if you don't have a statsd server you can configure to logger.info call the timings.

Comments

Chris Adams
It might be neat to add a Server-Timing header ( https://www.w3.org/TR/server-timing/) on the response so the values could show up in the Chrome Developer Tools — e.g. see the network tab for http://httpbin.org/response-headers?Server-Timing=dur=5;%20database.
Peter Bengtsson
Neat! I'm not sure what the need/use for rust might be but yeah, a decorator like this would work. Or a middleware.

Your email will never ever be published


Related posts

Previous:
Synonyms with elasticsearch-dsl 05 December 2017
Next:
How's My WiFi? 08 December 2017
Related by Keyword:
Welcome to the world django-fancy-cache! 01 March 2013
Newfound love of @staticmethod in Python 02 July 2012
Secs sell! How I cache my entire pages (server-side) 10 May 2012
Custom CacheMiddleware that tells Javascript a page is cached in Django 24 August 2009
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! Peterbe.com has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
Ever wondered how much $87 Billion is? 04 November 2003
Guake, not Yakuake or Yeahconsole 23 January 2010