svfat svfat - 29 days ago 6
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

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

middleware.py:

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 = datetime.now()

    def process_template_response(self, request, response):
        if not hasattr(response, 'data'):
            return response
        response.data = {
            'data': response.data,
            'meta': {
                'current_time' : datetime.now(),
                'benchmark': {
                    'time': datetime.now() - request._request_start_time,
                }
            }
        }
        return response