svfat svfat - 1 year ago 66
Python Question

Tastypie. How to add time of execution to responses?

I want to measure execution time for some queries and add this data to responses, like:

{"meta": {"execution_time_in_ms": 500 ...}}
I know how to add fields to tastypie's responses, but I haven't idea how to measure time in it, where I should initialize the timer and where I should stop it. Any ideas?

Answer Source

I found an answer, custom middleware is helpful in that case. It suits not only tastypie, but also DRF, and any another framework.

from datetime import datetime

class AddMetaMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

    def process_request(self, request):
        request._request_start_time =

    def process_template_response(self, request, response):
        if not hasattr(response, 'data'):
            return response = {
            'meta': {
                'current_time' :,
                'benchmark': {
                    'time': - request._request_start_time,
        return response
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download